package com.apes.fn.server.productRequire;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.scm.masterdata.enumeration.model.BusinessParam;
import com.apes.scm.masterdata.enumeration.repository.BusinessParamRepository;
import com.apes.fn.mdm.purchase.PurchasingGroupRepository;
import com.apes.fn.mdm.supplierConfiguration.SupplierBusinessScopeService;
import com.apes.fn.scm.contract.FnContract;
import com.apes.fn.scm.contract.FnContractRepository;
import com.apes.fn.scm.crossCompany.transfer.model.CrossCompanyTransferItemNew;
import com.apes.fn.scm.crossCompany.transfer.repository.TransferProductRepository;
import com.apes.fn.server.servicePlan.repository.ServicePlanItemRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.outbox.OutboxPayloadWrapper;
import com.apes.framework.plugin.outbox.OutboxSubscriberService;
import com.apes.framework.plugin.outbox.annotation.OutboxSubscriber;
import com.apes.framework.plugin.soe.store.database.repository.SceneRepository;
import com.apes.framework.util.*;
import com.apes.pi.service.PiManager;
import com.apes.scm.account.account.repository.InventoryBatchRepository;
import com.apes.scm.account.tax.model.Tax;
import com.apes.scm.account.tax.repository.TaxRepository;
import com.apes.scm.account.tax.service.TaxService;
import com.apes.scm.contract.model.Contract;
import com.apes.scm.contract.repository.ContractRepository;
import com.apes.scm.masterdata.contrast.model.ContrastPartyCode;
import com.apes.scm.masterdata.contrast.repository.ContrastPartyCodeRepository;
import com.apes.scm.masterdata.enumeration.repository.EnumerationRepository;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apes.scm.masterdata.party.model.AccessProvider;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.AccessProviderRepository;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.masterdata.product.model.ProductUom;
import com.apes.scm.masterdata.product.repository.ProductRepository;
import com.apes.scm.masterdata.product.repository.ProductUomRepository;
import com.apes.scm.masterdata.stock.model.Location;
import com.apes.scm.masterdata.stock.repository.LocationRepository;
import com.apes.scm.pur.purchaseOrder.model.PurchaseOrder;
import com.apes.scm.pur.purchaseOrder.model.PurchaseOrderItem;
import com.apes.scm.pur.purchaseOrder.repository.PurchaseOrderRepository;
import com.apes.scm.pur.purchaseOrder.service.PurchaseService;
import com.apes.scm.stock.transfer.model.Pick;
import com.apes.scm.stock.transfer.model.TransferItem;
import com.apes.scm.voucher.service.builder.CrossTransferVoucherBuilder;
import com.google.common.util.concurrent.AtomicDouble;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service("replenishmentManagementService")
public class ReplenishmentManagementService extends DomainService {
    @Autowired
    private EntityManager entityManager;
    @Autowired
    private ProductUomRepository productUomRepository;
    @Autowired
    private ProductRequireItemRepository productRequireItemRepository;
    @Autowired
    private InventoryBatchRepository inventoryBatchRepository;
    @Autowired
    private LocationRepository locationRepository;
    @Autowired
    private AutoProductRequireDumpService autoProductRequireDumpService;
    @Autowired
    private FnContractRepository fnContractRepository;
    @Autowired
    private ContractRepository contractRepository;
    @Autowired
    private PartyRoleRepository partyRoleRepository;
    @Autowired
    private BusinessParamRepository businessParamRepository;
    @Autowired
    private ProductRepository productRepository;
    @Autowired
    private TaxService taxService;
//    @Autowired
//    private CommodityInquiryItemRepository commodityInquiryItemRepository;
    @Autowired
    private DeptRepository deptRepository;
    @Autowired
    private PurchaseService purchaseService;
    @Value("${apes.switched:false}")
    private Boolean switched;
    @Autowired
    private OutboxSubscriberService outboxSubscriberService;
    @Autowired
    private PiManager piManager;
    @Autowired
    private SupplierBusinessScopeService supplierBusinessScopeService;
    @Autowired
    private ContrastPartyCodeRepository contrastPartyCodeRepository;
    @Autowired
    private ProductRequireService productRequireService;
    @Autowired
    private TransferProductRepository transferProductRepository;
    @Autowired
    private PurchasingGroupRepository purchasingGroupRepository;
    @Autowired
    private ThirdPartyOrder thirdPartyOrder;
    @Autowired
    private ProductRequireRepository productRequireRepository;

    /** 查询要货缺货明细 */
    public List queryRequireItem(SimpleRequest simpleRequest) {
        JSONObject getJO = simpleRequest.getJO();
        String sql = "SELECT B FROM ProductRequire T, ProductRequireItem B WHERE T.id = B.productRequire.id AND B.qtyRequire - B.qtyAssigned - B.qtyEnded - B.orderQty > 0 " +
                " AND ROWNUM <= 300 AND T.state not in ('create', 'delete') AND T.createDate >= :currentDate ";

        if (getJO.getBooleanValue("commodityInquiryOrderId")) sql += " AND B.commodityInquiryOrderId IS NOT NULL AND B.commodityInquiryOrderId NOT LIKE 'WC%' AND B.commodityInquiryOrderId NOT LIKE 'BI%' ";
        if (!StringUtils.isEmpty(getJO.get("id"))) sql += " and (T.id = :id or T.source = :id) ";
        if (!StringUtils.isEmpty(getJO.get("usage"))) sql += " and T.location.usage.id = :usageId ";
        if (!StringUtils.isEmpty(getJO.get("product"))) sql += " and B.product.id = :productId ";
        if (!StringUtils.isEmpty(getJO.get("location"))) sql += " and T.location.id = :locationId ";
        if (!StringUtils.isEmpty(getJO.get("brand"))) sql += " and B.product.brand.id = :brandId ";
        if (getJO.getBooleanValue("appRequire") == true) sql += " and T.channel.id in ('50', '70', '100') ";
        if (!StringUtils.isEmpty(getJO.get("serveType"))) sql += " and T.serveType.id = :serveTypeId ";
        if (!StringUtils.isEmpty(getJO.get("classify"))) sql += " and B.product.classify.id like :classifyId || '%'";
        if (getJO.get("requireDate") != null && getJO.getJSONArray("requireDate").size() != 0) sql += " and T.approveDate >= :requireDateS and T.approveDate <= :requireDateE ";
        if (!StringUtils.isEmpty(getJO.get("platform"))) sql += " and T.platform.id = :platformId ";
        if (!StringUtils.isEmpty(getJO.get("purchasingGroup")))
            sql += " and exists (select 1 from CommodityInquiryItem where commodityInquiryOrderId = B.commodityInquiryOrderId and productId.id = B.product.id and supplierId.id = B.supplier.id and purchasingGroup.id = :purchasingGroup) ";
        if (getJO.getBooleanValue("purchaseGroupIdIsNotNull")) sql += " AND B.purchasingGroup.id is not null";
        if (!StringUtils.isEmpty(getJO.get("fnCustomerExpandTemp"))) sql += " and T.customerExpand.carLicense = :fnCustomerExpandTempId ";
        sql += " order by T.id, T.approveDate desc ";

        Query query = entityManager.createQuery(sql);
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - 180);
        try {
            query.setParameter("currentDate", fmt.parse(fmt.format(calendar.getTime())));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        if (!StringUtils.isEmpty(getJO.get("id"))) query.setParameter("id", getJO.get("id"));
        if (!StringUtils.isEmpty(getJO.get("usage"))) query.setParameter("usageId", getJO.getJSONObject("usage").get("id"));
        if (!StringUtils.isEmpty(getJO.get("product"))) query.setParameter("productId", getJO.getJSONObject("product").get("id"));
        if (!StringUtils.isEmpty(getJO.get("location"))) query.setParameter("locationId", getJO.getJSONObject("location").get("id"));
        if (!StringUtils.isEmpty(getJO.get("brand"))) query.setParameter("brandId", getJO.getJSONObject("brand").get("id"));
        if (!StringUtils.isEmpty(getJO.get("serveType"))) query.setParameter("serveTypeId", getJO.getJSONObject("serveType").get("id"));
        if (!StringUtils.isEmpty(getJO.get("classify"))) query.setParameter("classifyId", getJO.getString("classify"));
        if (!StringUtils.isEmpty(getJO.get("purchasingGroup"))) query.setParameter("purchasingGroup", getJO.getJSONObject("purchasingGroup").getString("id"));
        if (!StringUtils.isEmpty(getJO.get("fnCustomerExpandTemp"))) query.setParameter("fnCustomerExpandTempId", getJO.getJSONObject("fnCustomerExpandTemp").getString("carLicense"));

        if (getJO.get("requireDate") != null && getJO.getJSONArray("requireDate").size() != 0) {
            SimpleDateFormat sdfTimeZone = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                query.setParameter("requireDateS", sdfTimeZone.parse(getJO.getJSONArray("requireDate").get(0).toString()));
                query.setParameter("requireDateE", sdfTimeZone.parse(getJO.getJSONArray("requireDate").get(1).toString()));
            } catch (Exception e) {
            }
        }

        if (!StringUtils.isEmpty(getJO.get("platform"))) query.setParameter("platformId", getJO.getJSONObject("platform").get("id"));
        List<ProductRequireItem> productRequireItemList = query.getResultList();
        List returnData = new ArrayList();
        productRequireItemList.forEach(requireItem -> {
            this.appendProductRequireItes(requireItem, returnData);
        });
        if (returnData.size() == 0) throw new RuntimeException("未找到可补货数据!");
        return returnData;

    }

    /** 要货 转储缺货明细汇总 */
    public JSONObject requireItemSum(SimpleRequest request) {
        JSONObject getJO = request.getJO();

        // 根据要货单和仓库分组汇总
        AtomicBoolean isCheck = new AtomicBoolean(false);
        AtomicReference appendRequireId = new AtomicReference(""); // 生成转储时用来确定分配哪些要货单
        Map<Object, List<Object>> groupRequires = getJO.getJSONArray("productRequireItems").stream().collect(Collectors.groupingBy(item -> {
            JSONObject itemObj = (JSONObject) item;
            if (itemObj.getBooleanValue("selectFlag")) isCheck.getAndSet(true);
            String requireIds = appendRequireId.get().toString();
            String productId = itemObj.getJSONObject("product").getString("id");
            String locationId = itemObj.getJSONObject("location").getString("id");
            String productRequireId = itemObj.getString("productRequireId");
            if (StringUtils.isEmpty(requireIds) || requireIds.indexOf(productRequireId) == -1) appendRequireId.set(appendRequireId.get() + productRequireId + ",");
            return locationId + productId + itemObj.getJSONObject("uom").getString("id");
        }));
        if (!isCheck.get() && !"notReplenishmentCompleted".equals(getJO.get("originMethod"))) throw new RuntimeException("请先勾选数据!");

        // 根据分组后的数据循环汇总明细缺货数量
        JSONArray groupItemArray = new JSONArray();
        AtomicReference requireIdStr = new AtomicReference();
        groupRequires.forEach((k, v) -> {
            JSONObject obj = new JSONObject();
            AtomicDouble sumDumpQty = new AtomicDouble(0);
            v.stream().forEach(groupRequireItems -> {
                JSONObject groupRequireItemObj = (JSONObject) groupRequireItems;
                if (groupRequireItemObj.getBooleanValue("selectFlag")) {
                    String requireId = groupRequireItemObj.getString("productRequireId");
                    double requireQty = groupRequireItemObj.getDoubleValue("qtyRequire");
                    double assignedQty = groupRequireItemObj.getDoubleValue("qtyAssigned");
                    double endQty = groupRequireItemObj.getDoubleValue("qtyEnded");
                    double orderQty = groupRequireItemObj.getDoubleValue("orderQty");
                    double endResultQty = requireQty - assignedQty - endQty - orderQty;

                    if (endResultQty > 0) sumDumpQty.set(sumDumpQty.get() + endResultQty);
                    if (StringUtils.isEmpty(requireIdStr.get())) {
                        requireIdStr.set("'" + requireId + "'");
                    } else if (requireIdStr.get().toString().indexOf(requireId) == -1) {
                        requireIdStr.set(requireIdStr.get() + ",'" + requireId + "'");
                    }
                }
            });
            if (sumDumpQty.get() == 0) return;
            JSONObject oneRequireItem = (JSONObject) v.get(0);
            String productId = oneRequireItem.getJSONObject("product").getString("id");
            long uomId = oneRequireItem.getJSONObject("uom").getLong("id");
            obj.put("location", oneRequireItem.getJSONObject("location"));
            obj.put("product", oneRequireItem.getJSONObject("product"));
            obj.put("canAssignableQty", 0);
            obj.put("distributionQty", 0);

            ProductUom dumpUom = productUomRepository.findByProductId(productId);
            ProductUom requireUom = productUomRepository.findOne(uomId);
            double toBeReplenishedQty = Math.ceil(requireUom.computeQty(sumDumpQty.get(), dumpUom, false));
            obj.put("toBeReplenishedQty", toBeReplenishedQty);
            obj.put("uom", dumpUom);
            obj.put("requireUom", oneRequireItem.getJSONObject("uom"));
            groupItemArray.add(obj);
        });
        JSONObject returnData = new JSONObject();
        returnData.put("allRequireId", appendRequireId.get());
        returnData.put("requireIdStr", requireIdStr.get());
        returnData.put("sumProductRequireItems", groupItemArray);
        return returnData;
    }

    /** 要货缺货获取有效库存 */
    public JSONObject getStock(SimpleRequest request) {
        JSONObject getJO = request.getJO();
        String FlocationCompayId = getJO.getJSONObject("location").getJSONObject("company").getString("id");
        String locationId = getJO.getJSONObject("location").getString("id");
        PartyRole fLocationCompany = partyRoleRepository.findOne(FlocationCompayId);
        String fOperator = fLocationCompany.getParty().getCorporate().getOperation().getId();
        // 按 [商品、运营模式] 分组
        Map<Object, List<Object>> groupRequires = getJO.getJSONArray("sumProductRequireItems").stream().collect(Collectors.groupingBy(item -> {
            JSONObject itemObj = (JSONObject) item;
            JSONObject returnK = new JSONObject();
            returnK.put("productId", itemObj.getJSONObject("product").getString("id"));
//            if ("001072".equals(fOperator)) {
                PartyRole cLocationCompany = partyRoleRepository.findOne(itemObj.getJSONObject("location").getJSONObject("company").getString("id"));
                String cOperator = cLocationCompany.getParty().getCorporate().getOperation().getId();
//                if ("001073".equals(cOperator)) returnK.put("isDirectlyChangeEmpower", true);
//            }
            returnK.put("operator", cOperator);
            returnK.put("isNotCross", FlocationCompayId.equals(cLocationCompany.getId()));
            return returnK;
        }));

        groupRequires.forEach((k, v) -> {
            JSONObject kObj = (JSONObject) k;
            String productId = kObj.getString("productId");
            String cOperator = kObj.getString("operator");
            boolean isNotCross = kObj.getBooleanValue("isNotCross");
            Map availableStocks = productRequireItemRepository.availableStock(locationId, productId);

            // 获取对应商品可分配库存
            if (!isNotCross) availableStocks = autoProductRequireDumpService.getVaildStock(fOperator, cOperator, locationId, productId/*, availableStocks*/);
       /*     if ("1001".equals(FlocationCompayId)) {
                availableStocks = productRequireItemRepository.availableStock(locationId, productId);
            } else {
                availableStocks = inventoryBatchRepository.sumSupplierInventory(k.toString(), FlocationCompayId, "G1001", locationId);
            }*/
            if (availableStocks.size() == 0) return;
            ProductUom dumpUom = productUomRepository.findByProductId(productId);
            ProductUom oneUom = productUomRepository.findAll(JpaDsl.toCriteriaByEq("uomCategory.id", productId, "factor", 1)).get(0);
            double usableQty = Math.floor(oneUom.computeQty(Double.parseDouble(availableStocks.get("USABLE_QTY").toString()), dumpUom, false));
            AtomicDouble canAssignableQty = new AtomicDouble(usableQty);
            AtomicDouble originCanAssignableQty = new AtomicDouble(usableQty); // 存储最原始的分配数

            // 根据单位分组
            Map<Object, List<Object>> accordingUomGroupRequireItem = v.stream().collect(Collectors.groupingBy(requireItems -> {
                JSONObject requireItemsObj = (JSONObject) requireItems;
                return requireItemsObj.getJSONObject("requireUom").getLong("id");
            }));

            accordingUomGroupRequireItem.forEach((kUom, sumRequireDumps) -> {
                // 循环分配数量
                sumRequireDumps.stream().anyMatch(sumRequireDump -> {
                    JSONObject needDumpRequire = (JSONObject) sumRequireDump;
                    double toBeReplenishedQty = needDumpRequire.getDoubleValue("toBeReplenishedQty");
                    if (canAssignableQty.get() <= 0) return true;
                    if (canAssignableQty.get() < toBeReplenishedQty) {
                        needDumpRequire.put("distributionQty", canAssignableQty.get());
                        canAssignableQty.set(0);
                    } else {
                        needDumpRequire.put("distributionQty", toBeReplenishedQty);
                        canAssignableQty.set(canAssignableQty.get() - toBeReplenishedQty);
                    }
                    return false;
                });
            });

            // 循环设置可分配数
            accordingUomGroupRequireItem.forEach((kUom, sumRequireDumps) -> {
                sumRequireDumps.forEach(sumRequireDump -> {
                    JSONObject needDumpRequire = (JSONObject) sumRequireDump;
                    if (needDumpRequire.getDoubleValue("distributionQty") == 0) needDumpRequire.put("distributionQty", 0);
                    if (needDumpRequire.getDoubleValue("canAssignableQty") == 0) needDumpRequire.put("canAssignableQty", 0);
                    needDumpRequire.put("canAssignableQty", canAssignableQty.get());
                    needDumpRequire.put("backupCanAssignableQty", originCanAssignableQty.get());
                });
            });
        });
        return getJO;
    }


    /** 要货转储 */
    public JSONObject requireDump(SimpleRequest request) {
        JSONObject getJO = request.getJO();
        if (getJO.getJSONObject("location") == null) throw new RuntimeException("请选择配货仓库 !");
        Location fLocation = locationRepository.findOne(getJO.getJSONObject("location").getString("id"));
        AtomicBoolean isNotCross = new AtomicBoolean(true);
        String fCompanyId = fLocation.getCompany().getId();
        String requireIdStr = getJO.getString("requireIdStr");

        // 根据仓库分组
        Map<Object, List<Object>> groupRequires = getJO.getJSONArray("sumProductRequireItems").stream().collect(Collectors.groupingBy(item -> {
            JSONObject itemObj = (JSONObject) item;
            return itemObj.getJSONObject("location").getString("id");
        }));

        // 分组后循环配货
        List assignDumpTime = new ArrayList();
        AtomicDouble dumpQty = new AtomicDouble(0);
        groupRequires.forEach((key, value) -> {
            Location cLocation = locationRepository.findOne(key.toString());
            String cCompanyId = cLocation.getCompany().getId();
            isNotCross.set(fCompanyId.equals(cCompanyId));
            Map singleRequireItemMap = new HashMap();
            Set<TransferItem> transferItems = new HashSet<>();
            Set<CrossCompanyTransferItemNew> crossCompanyTransferItems = new HashSet<>();
            value.forEach(requireItems -> {
                JSONObject itemObj = (JSONObject) requireItems;
                double distributionQty = itemObj.getDoubleValue("distributionQty");
                if (itemObj.getBooleanValue("checkData") && distributionQty > 0) {
                    String productId = itemObj.getJSONObject("product").getString("id");
                    singleRequireItemMap.put("PRODUCT_ID", productId);
                    singleRequireItemMap.put("RABBET", distributionQty);
                    singleRequireItemMap.put("PRODUCT_UOM_ID", itemObj.getJSONObject("requireUom").getString("id"));
                    singleRequireItemMap.put("LOCATION_ID", key.toString());
                }
            });
            // 要货转储数据分配
            if (singleRequireItemMap.size() == 0) return;
            autoProductRequireDumpService.dumpDistribution(singleRequireItemMap, fLocation, cLocation, isNotCross.get(), transferItems, crossCompanyTransferItems, false,
                    new HashMap(), new HashMap(), new HashMap());

            Map expandContent = new HashMap();
            expandContent.put("type", "replenishmentManagement");
            expandContent.put("note", "要货补货管理转储");
            expandContent.put("source", "");
            expandContent.put("sourceBusinessType", "ProductRequire");
//            expandContent.put("sourceKeys_", getJO.getString("allRequireId"));
            expandContent.put("sourceKeys_", requireIdStr.replaceAll("'","")); // 制定需要分配那些要货单
            expandContent.put("personId", request.getPersonId());
            boolean appRequire = getJO.getJSONObject("queryCondiAndItem").getBooleanValue("appRequire");
            assignDumpTime.add(DateUtil.format(new Date(), DateUtil.SHOW_DATETIME_FORMAT));
//            autoProductRequireDumpService.dumpApproveAssign(isNotCross.get(), transferItems, crossCompanyTransferItems, fLocation, cLocation, expandContent, new HashMap(), appRequire?"03":"无");
            assignDumpTime.add(DateUtil.format(new Date(), DateUtil.SHOW_DATETIME_FORMAT));
            // 判断是否要同步老框架
//            autoProductRequireDumpService.batchDumpSynOldFrame(dumpId);
            dumpQty.set(dumpQty.get() + 1);
        });
        if (dumpQty.get() == 0) throw new RuntimeException("未获取到有效数据！请检查是否填写转储数量");

        List requireIdStrNew = Arrays.asList(requireIdStr.replaceAll("'", "").split(","));
        List dumpIds = SpringManager.getBean(ProductRequireExpandRepository.class).replemeDumpGetId(requireIdStrNew, assignDumpTime.get(0).toString(), assignDumpTime.get(1).toString());
        String numberContent = "转储成功! \r\n";
        for (int i = 0, iLen = dumpIds.size(); i < iLen; i++) {
            Map dumpIdM = (Map)dumpIds.get(i);
            numberContent += dumpIdM.get("origin").toString() + " - " + dumpIdM.get("DISTRIBUTION_ID") + "\r\n";
        }
        JSONObject remainderData = this.notReplenishmentCompleted(getJO);
        if (dumpIds.size() > 0) {
            remainderData.put("sucessNumber", numberContent);
        } else {
            throw new RuntimeException("转储失败, 请检查发货仓库是否又库存、批次");
        }
        return remainderData;
    }


    /** 转储成功后判断是否还有数据生成 */
    private JSONObject notReplenishmentCompleted(JSONObject param) {

        JSONObject cloneParam = (JSONObject) param.clone();
        JSONObject cloneQueryCondiAndItem = cloneParam.getJSONObject("queryCondiAndItem");
        cloneQueryCondiAndItem.remove("sumProductRequireItems");
        JSONArray oldProductRequireItems = cloneQueryCondiAndItem.getJSONArray("productRequireItems");


        JSONObject queryCondiAndItem = param.getJSONObject("queryCondiAndItem");
        SimpleRequest request = new SimpleRequest();
        queryCondiAndItem.remove("productRequireItems");
        request.setData(queryCondiAndItem);
        List dumpRequires = new ArrayList();
        try {
            dumpRequires = this.queryRequireItem(request);
        } catch (Exception e) {
            if (e.getMessage().indexOf("未找到可补货数据!") != -1) {
                JSONObject returnData = new JSONObject();
                returnData.put("sumProductRequireItems", new JSONArray());
                return returnData;

            }
            throw new RuntimeException(e.getMessage());
        }


        queryCondiAndItem.put("productRequireItems", appendItem(dumpRequires, oldProductRequireItems));
        queryCondiAndItem.put("originMethod", "notReplenishmentCompleted");
        request = new SimpleRequest();
        request.setData(queryCondiAndItem);
        JSONObject canDumpObjAndCondi = this.requireItemSum(request);
        canDumpObjAndCondi.putAll(cloneParam.getJSONObject("queryCondiAndItem"));

        canDumpObjAndCondi.put("location", param.getJSONObject("location"));
        request = new SimpleRequest(); // 需判断库存是否正确
        request.setData(canDumpObjAndCondi);
        JSONObject returnData = this.getStock(request);
        return returnData;
    }

    /** 数据溢出，重新拼接数据 */
    private List appendItem(List dumpRequires, JSONArray oldProductRequireItems) {
        List returnNewDumpRequires = new ArrayList();
        oldProductRequireItems.forEach(oldProductRequireItem -> {
            JSONObject oldRequireItemObj = (JSONObject) oldProductRequireItem;
            String requireItemId = oldRequireItemObj.getString("id");
            String selectFlag = oldRequireItemObj.getString("selectFlag");
            String hideSelected = oldRequireItemObj.getString("hideSelected");
            String selected = oldRequireItemObj.getString("selected");
            dumpRequires.forEach(item -> {
                Map itemMap = (Map) item;
                if (requireItemId.equals(itemMap.get("id").toString())) {
                    JSONObject detailedObj = new JSONObject();
                    JSONObject newObj = new JSONObject();
                 /*   detailedObj.put("id", ((Product)itemMap.get("product")).getId());
                    detailedObj.put("name", ((Product)itemMap.get("product")).getName());*/
                    newObj.put("product", /*detailedObj*/itemMap.get("product"));


                    if (itemMap.get("customerExpand") != null) {
                      /*  detailedObj = new JSONObject();
                        detailedObj.put("id", ((FnCustomerExpand)itemMap.get("customerExpand")).getId());
                        detailedObj.put("name", ((FnCustomerExpand)itemMap.get("customerExpand")).getCarLicense());*/
                        newObj.put("customerExpand", /*detailedObj*/itemMap.get("customerExpand"));
                    }

                    newObj.put("qtyAssigned", itemMap.get("qtyAssigned"));
                    newObj.put("approveDate", itemMap.get("approveDate"));
                    newObj.put("source", itemMap.get("source"));
                    newObj.put("qtyRequire", itemMap.get("qtyRequire"));
                    newObj.put("selectFlag", selectFlag);

               /*     detailedObj = new JSONObject();
                    detailedObj.put("id", ((PartyRole)itemMap.get("platform")).getId());
                    detailedObj.put("name", ((PartyRole)itemMap.get("platform")).getParty().getName());*/
                    newObj.put("platform", /*detailedObj*/itemMap.get("platform"));

                    newObj.put("toBeReplenishedQty", itemMap.get("toBeReplenishedQty"));

                  /*  detailedObj = new JSONObject();
                    detailedObj.put("id", ((ProductUom)itemMap.get("uom")).getId());
                    detailedObj.put("name", ((ProductUom)itemMap.get("uom")).getName());*/
                    newObj.put("uom", /*detailedObj*/itemMap.get("uom"));

                    newObj.put("qtyEnded", itemMap.get("qtyEnded"));
                    newObj.put("hideSelected", hideSelected);

                    if (itemMap.get("supplier") != null) {
                      /*  detailedObj = new JSONObject();
                        detailedObj.put("id", ((PartyRole)itemMap.get("supplier")).getId());
                        detailedObj.put("name", ((PartyRole)itemMap.get("supplier")).getParty().getName());*/
                        newObj.put("supplier", /*detailedObj*/itemMap.get("supplier"));
                    }

                    newObj.put("orderQty", itemMap.get("orderQty"));

                   /* detailedObj = new JSONObject();
                    detailedObj.put("id", ((Location)itemMap.get("location")).getId());
                    detailedObj.put("name", ((Location)itemMap.get("location")).getName());

                    JSONObject detailedObj2 = new JSONObject();
                    detailedObj2.put("id", ((Location)itemMap.get("location")).getCompany().getId());
                    detailedObj.put("company", detailedObj2);*/

                    newObj.put("location", /*detailedObj*/itemMap.get("location"));

                    newObj.put("id", itemMap.get("id"));
                    newObj.put("selected", selected);
                    newObj.put("commodityInquiryOrderId", itemMap.get("commodityInquiryOrderId"));
                    newObj.put("productRequireId", itemMap.get("productRequireId"));
                    returnNewDumpRequires.add(newObj);
                }
            });
        });
        return returnNewDumpRequires;
    }


    /** 获取采购订单所需要的信息 */
    public JSONObject purchaseNeedInfo(SimpleRequest request) {
        JSONObject getJO = request.getJO();
        JSONArray newRequireItems = new JSONArray();
        AtomicBoolean isCheck = new AtomicBoolean(false);
        getJO.getJSONArray("productRequireItems").stream().forEach(requireItems -> {
            JSONObject requireItemObj = (JSONObject) requireItems;
            boolean selectFlag = requireItemObj.getBooleanValue("selectFlag");
            // 获取供应商、价格等信息返回
            if (selectFlag) {
                requireItemObj.put("originMethod", getJO.getString("originMethod"));
                JSONObject newPurchaseRequireItems = this.appendReturnPurchaseRequireItem(requireItemObj/*, newPurchaseRequireItems*/);
                if (newPurchaseRequireItems.size() != 0) newRequireItems.add(newPurchaseRequireItems);
                isCheck.getAndSet(selectFlag);
            }
        });
        if (!isCheck.get()) throw new RuntimeException("请先勾选数据!");
        getJO.put("purchaseRequireItems", newRequireItems);
        return getJO;
    }

    /** 要货管理--采购补货界面--弹出框获取价格 */
    /*public Page<Map> getAllPrice(SimpleRequest request) {
        JSONObject getJO = request.getJO();
        JSONObject currentData = getJO.getJSONObject("conditionModel").getJSONObject("node");
        JSONObject product = currentData.getJSONObject("product");
        String productId = product.getString("id");
        Location location = locationRepository.findOne(currentData.getJSONObject("location").getString("id"));
        double distributionQty = currentData.getDoubleValue("distributionQty");
        double toBeReplenishedQty = currentData.getDoubleValue("toBeReplenishedQty");
        double newDistributionQty = distributionQty > 0?distributionQty:toBeReplenishedQty;
        ProductUom minFactorUom = productUomRepository.findAll(JpaDsl.toCriteriaByEq("factor", 1, "uomCategory.id", productId)).get(0);

        List suppliers = new ArrayList();
        JSONArray priceArray = this.getPrice("", productId, "", currentData, "getAllPrice");

        priceArray.forEach(singlePrice -> {
            JSONObject singlePriceObj = (JSONObject) singlePrice;
            suppliers.add(singlePriceObj.getString("SUPPLIER_ID"));
        });

        // 获取合同
        if (suppliers.size() == 0) throw new RuntimeException("未找到相关价格供应商 ！");
        List<Contract> contractList = this.getSupplierContract(location.getCompany().getId(), suppliers, "", new ArrayList());
        JSONArray returnDataArray = new JSONArray();
        contractList.forEach(contract -> {
            JSONObject returnDataObj = new JSONObject();
            returnDataObj.put("id", currentData.getString("id"));
            returnDataObj.put("product", currentData.getJSONObject("product"));
            returnDataObj.put("uom", currentData.getJSONObject("purchaseUom"));
            returnDataObj.put("distributionQty", newDistributionQty);
            returnDataObj.put("supplier", contract.getPartner());
            returnDataObj.put("contract", contract);
            returnDataObj.put("contractCompany", contract.getCompany()); // 用来做前端展示价格文件属于哪个平台


            String contractCompanyId = contract.getCompany().getId();
            boolean isPlatForm = "1007".equals(contractCompanyId);
            PartyRole company = isPlatForm?location.getCompany():contract.getCompany();
            Dept dept = isPlatForm?deptRepository.findAll(JpaDsl.toCriteriaByEq("company.id", company.getId(), "deptType.id", "000006")).get(0):contract.getDept();
            returnDataObj.put("company", company);
            returnDataObj.put("dept", dept);
            returnDataObj.put("cooperation", contract.getCooperation());
            this.getTax(contract.getPartner().getId(), productId, returnDataObj);
            // 获取价格
            JSONObject singlePriceSupplier = (JSONObject) priceArray.stream().filter(singlePrice -> {
                JSONObject singlePriceObj = (JSONObject) singlePrice;
                    return contract.getPartner().getId().equals(singlePriceObj.getString("SUPPLIER_ID"));
            }).findFirst().orElse(new JSONObject());

            ProductUom puchaseUom = productUomRepository.findOne(currentData.getJSONObject("purchaseUom").getLong("id"));
            double P001 = singlePriceSupplier.getDoubleValue("P001");
            double P902 = singlePriceSupplier.getDoubleValue("P902");
            P001 = this.getUnP001(P001, singlePriceSupplier.getDoubleValue("P101"), isPlatForm, singlePriceSupplier.getString("XJBJ"));
            returnDataObj.put("P001", minFactorUom.computePrice(P001, puchaseUom));
            returnDataObj.put("amount", newDistributionQty * returnDataObj.getDoubleValue("P001"));
            if (P902 == 0 && P001 != 0) {
                JSONObject getCeilPrice = new JSONObject();
                try {
                    getCeilPrice = purchaseService.getPurcherPrice(contractCompanyId, contract.getPartner().getId(), productId, "");
                } catch (Exception e) {
                }
                P902 = getCeilPrice.getDoubleValue("P902");
            }
            returnDataObj.put("priceCeiling", minFactorUom.computePrice(P902, puchaseUom));
            if (P001 != 0 && P902 != 0) returnDataArray.add(returnDataObj);
        });

        Pageable pageable = PageRequest.of(getJO.getIntValue("page"), getJO.getIntValue("size"));
        PageImpl page = new PageImpl<>(returnDataArray, pageable, returnDataArray.size());
        return page;
    }*/

    public Page<Map> getAllPrice(SimpleRequest request) {
        JSONObject getJO = request.getJO();
        JSONObject currentData = getJO.getJSONObject("conditionModel").getJSONObject("node");
        JSONObject product = currentData.getJSONObject("product");
        String productId = product.getString("id");
        String locationCompanyId = currentData.getJSONObject("location").getJSONObject("company").getString("id");
        ProductUom minFactorUom = productUomRepository.findAll(JpaDsl.toCriteriaByEq("factor", 1, "uomCategory.id", productId)).get(0);

        JSONArray returnDataArray = new JSONArray();
        JSONArray priceArray = getPrice("", productId, "", currentData, "getAllPrice", locationCompanyId); // 没有公司能否返回最准确得 最低现价等
        List supplierIds = getPriceSupplier(priceArray);
        if (supplierIds.size() == 0) throw new RuntimeException("未找到相关价格 ！");
        supplierIds.add("占位");
        List<Contract> contractList = this.getContract(locationCompanyId, supplierIds);
        contractList.forEach(contract -> {
            String contractType = contract.getContractType().getId();
            priceArray.forEach(singlePrice -> {
                JSONObject singlePriceObj = (JSONObject) singlePrice;
                String companyId = singlePriceObj.getString("COMPANY_ID");
                JSONObject returnDataObj = this.appendAllPriceDataReturn(contract, currentData, singlePriceObj, minFactorUom);

                if (StringUtils.isEmpty(companyId) || contractType.equals("Contract.contractType.platform") || (!StringUtils.isEmpty(companyId) && companyId.equals(contract.getCompany().getId()) && !contractType.equals("Contract.contractType.platform"))) {
                    if (singlePriceObj.getString("SUPPLIER_ID").equals(contract.getPartner().getId()) && singlePriceObj.getDoubleValue("P001") > 0 && returnDataObj.getDoubleValue("P902") > 0) {
                        returnDataArray.add(returnDataObj);
                    }
                }
            });
        });
        Pageable pageable = PageRequest.of(getJO.getIntValue("page"), getJO.getIntValue("size"));
        PageImpl page = new PageImpl<>(returnDataArray, pageable, returnDataArray.size());
        return page;
    }

    // 查询单个商品所有价格文件数据返回
    private JSONObject appendAllPriceDataReturn(Contract contract, JSONObject currentData, JSONObject singlePriceObj, ProductUom minFactorUom) {
        double distributionQty = currentData.getDoubleValue("distributionQty");
        double toBeReplenishedQty = currentData.getDoubleValue("toBeReplenishedQty");
        double newDistributionQty = distributionQty > 0?distributionQty:toBeReplenishedQty;
        String productId = currentData.getJSONObject("product").getString("id");

        JSONObject returnDataObj = new JSONObject();
        returnDataObj.put("id", currentData.getString("id"));
        returnDataObj.put("product", currentData.getJSONObject("product"));
        returnDataObj.put("uom", currentData.getJSONObject("purchaseUom"));
        returnDataObj.put("distributionQty", newDistributionQty);
        returnDataObj.put("supplier", contract.getPartner());
        returnDataObj.put("contract", contract);
        returnDataObj.put("contractCompany", contract.getCompany()); // 用来做前端展示价格文件属于哪个平台

        String contractCompanyId = contract.getCompany().getId();
        boolean isPlatForm = "1007".equals(contractCompanyId);
        String locationCompanyId = currentData.getJSONObject("location").getJSONObject("company").getString("id");
        String operation = invoke("purchase.order.getModel", MapUtil.mapper("companyId", locationCompanyId));
        if (isPlatForm/*"empower".equals(operation)*/) {
            String locationCompanyName = currentData.getJSONObject("location").getJSONObject("company").getString("name");
            returnDataObj.put("dept", deptRepository.findAll(JpaDsl.toCriteriaByEq("company.id", locationCompanyId, "deptType.id", "000006")).get(0));
            returnDataObj.put("company", MapUtil.mapper("id", locationCompanyId, "name", locationCompanyName));
        } else {
            returnDataObj.put("company", MapUtil.mapper("id", contract.getCompany().getId(), "name", contract.getCompany().getName()));
            returnDataObj.put("dept", contract.getDept());
        }

        returnDataObj.put("cooperation", contract.getCooperation());
        this.getTax(returnDataObj.getJSONObject("company").getString("id"), contract.getPartner().getId(), productId, returnDataObj);

        ProductUom puchaseUom = productUomRepository.findOne(currentData.getJSONObject("purchaseUom").getLong("id"));
        double P001 = singlePriceObj.getDoubleValue("P001"); // ??????
        double P902 = singlePriceObj.getDoubleValue("P902");
        P001 = this.getUnP001(P001, singlePriceObj.getDoubleValue("P101"), isPlatForm, singlePriceObj.getString("XJBJ"));
        returnDataObj.put("P001", minFactorUom.computePrice(P001, puchaseUom));
        returnDataObj.put("amount", newDistributionQty * returnDataObj.getDoubleValue("P001"));
        if (P902 == 0 && P001 != 0) {
            JSONObject getCeilPrice = new JSONObject();
            try {
                getCeilPrice = purchaseService.getPurcherPrice(contractCompanyId.equals("1007")? locationCompanyId:contractCompanyId, contract.getPartner().getId(), productId, "");
            } catch (Exception e) {
            }
            P902 = getCeilPrice.getDoubleValue("P902"); // ???? 不应该取二遍
            returnDataObj.put("P902", P902);
        } else {
            returnDataObj.put("P902", P902);
        }

        returnDataObj.put("priceCeiling", minFactorUom.computePrice(P902, puchaseUom));
//        if (P001 != 0 && P902 != 0) returnDataArray.add(returnDataObj);
        return returnDataObj;
    }

    /** 提供第三方调用 */
    public List thirdPartyQueryContract(SimpleRequest request) {
        JSONObject getJO = request.getJO();
        List supplierId = getJO.getJSONArray("supplierId");
        List notinSupplier = getJO.getJSONArray("notinSupplier");
        List<Contract> contractList = (List<Contract>) this.getSupplierContract(getJO.getString("companyId"), supplierId, getJO.getString("type"), notinSupplier).stream().distinct().collect(Collectors.toList());
        if (contractList.size() == 0) throw new RuntimeException("未找到有效供应商合同！");

//        Map<Object, List<Object>> groupContracts = contractList.stream().collect(Collectors.groupingBy(contract -> {return ((Contract) contract).getPartner().getId();}));
//
//        List reponseContracts = new ArrayList<>();
//        groupContracts.forEach((k, v) -> {
//            reponseContracts.addAll(v);
//        });
        return contractList;
    }

    /** 获取供应商、合同 */
    private List<Contract> getSupplierContract(String companyId, List supplierId, String type, List notinSupplier) {
        List<Contract> contracts = new ArrayList<>();
        List<Contract> contractList = new ArrayList<>();
        List companys = new ArrayList();
        List businessCompanys = new ArrayList();
        companys.add(companyId);
        businessCompanys.add(companyId); // 存在 1001 公司合同

        String cloneCompanyId = companyId;
        String supplierIds = "", contractName = "", contractId = "", partnerName = "";
        supplierIds = supplierId.get(0).toString();
        contractName = supplierIds;
        contractId = supplierIds;
        partnerName = supplierIds;

        PartyRole partyRole = partyRoleRepository.findOne(companyId);
        String operation = SpringManager.getBean(CrossTransferVoucherBuilder.class).getModel(partyRole);
        operation = "empower".equals(operation)?"001073":"subsidiary".equals(operation)?"001661":"001072";
        List<PartyRole> roles = partyRoleRepository.findAll(JpaDsl.toCriteriaByEq("party.id", partyRole.getParty().getId(), "role.id", "Warehousing"));
        if (roles.size() > 0) {
            if ("purchaseOrder".equals(type)) {
                List tempCompanys = new ArrayList();
                tempCompanys.add("1007");
                contractList = contractRepository.queryPlatformContract(tempCompanys, "Contract.contractType.platform", supplierIds, contractName, contractId, partnerName, notinSupplier);
            } else {
                contractList = contractRepository.qryValidContractNotSupplier("1007", "Contract.contractType.platform");
            }
            return contractList;
        }

        // 查找赋能合同
        List<FnContract> fnContractList = fnContractRepository.qryValidFnContract(companyId);
        // 根据赋能合同主方查找平台协议合同
        if (fnContractList.size() != 0) {
            String fnCompanyId = fnContractList.get(0).getCompany().getId();
            companys.add(fnCompanyId);
            if ("purchaseOrder".equals(type)) {
                contractList = contractRepository.queryPlatformContract(companys, "Contract.contractType.platform", supplierIds, contractName, contractId, partnerName, notinSupplier);
                if (contractList.size() > 0) contracts.addAll(contractList);
                if (contractList.size() == 0 && StringUtils.isEmpty(supplierIds)) contractList = contractRepository.qryValidContractNotSupplier(fnCompanyId, "Contract.contractType.platform");
            }/* else {
                contractList = contractRepository.qryValidContractNotSupplier(fnCompanyId, "Contract.contractType.platform");
            }*/

//            companyId = fnCompanyId;
            if (!"purchaseOrder".equals(type)) contracts.addAll(contractList);
        }

        // 根据对照表找采购合同
        List<BusinessParam> businessParams = businessParamRepository.accordingToCompanyContract(companys);
        businessParams.forEach(singleBusiness -> businessCompanys.add(singleBusiness.getValue()));
//        if (businessParams.size() > 0) companyId = businessParams.get(0).getValue();
        List<Contract> purchaseContracts = new ArrayList<>();
        if ("purchaseOrder".equals(type)) {
            if ("001073".equals(operation)) {
                purchaseContracts = contractRepository.qrylikeContract(businessCompanys, "Contract.contractType.supplier", supplierIds, contractName, contractId, partnerName, notinSupplier);
                purchaseContracts.addAll(contractRepository.qrylikeContract(businessCompanys, "Contract.contractType.supplier", supplierIds, contractName, contractId, partnerName, notinSupplier));
//                if (purchaseContracts.size() == 0) purchaseContracts = contractRepository.qrylikeContract(cloneCompanyId, "Contract.contractType.supplier", supplierIds, contractName, contractId, partnerName, notinSupplier);
            } else {
                purchaseContracts = contractRepository.queryPlatformContract(businessCompanys, "Contract.contractType.supplier", supplierIds, contractName, contractId, partnerName, notinSupplier);
            }
        } /*else {
            purchaseContracts = contractRepository.qryValidContract(companyId, "Contract.contractType.supplier", supplierId);
        }*/
        if (purchaseContracts.size() != 0) contracts.addAll(purchaseContracts);
        return contracts;
    }

    /** 获取价格 */
   /* private JSONArray getPrice(String supplierId, String productId, String upstreamCompanyId, *//*String commodityInquiryOrderId*//*JSONObject items, String method) {
        Map getPriceParam = new HashMap();
        getPriceParam.put("SYS_RQ", new Date());
        getPriceParam.put("conditionId", "T03");
        getPriceParam.put("PRODUCT_ID", productId);
        Product product = productRepository.findOne(productId);
        getPriceParam.put("BRAND_ID", product.getBrand().getId());
        getPriceParam.put("CLASSIFY_ID", product.getClassify().getId());

        String commodityInquiryOrderId = items.getString("commodityInquiryOrderId");
        JSONArray reponsePriceArray = new JSONArray();
        if (StringUtils.hasText(commodityInquiryOrderId) && !"getAllPrice".equals(method)) {
            this.getSPXJDZXB(items, productId, commodityInquiryOrderId, upstreamCompanyId, reponsePriceArray);

        } else if (!StringUtils.isEmpty(supplierId) && !StringUtils.isEmpty(upstreamCompanyId)) {
            getPriceParam.put("SYS_DIM_FIELD", "COMPANY_ID,PRODUCT_ID");
            getPriceParam.put("SYS_NO_CHECK", "SUPPLIER_ID");
            getPriceParam.put("SUPPLIER_ID", supplierId);
            getPriceParam.put("COMPANY_ID", upstreamCompanyId);
            reponsePriceArray = (JSONArray) JSON.parse(invoke("condition.getCondition_Muti", getPriceParam).toString());
        } else if (StringUtils.isEmpty(supplierId) && StringUtils.isEmpty(upstreamCompanyId)) {
            getPriceParam.put("SYS_DIM_FIELD", "PRODUCT_ID");
            getPriceParam.put("SYS_NO_CHECK", "SUPPLIER_ID,COMPANY_ID,CAR_LICENSE");
            JSONArray result = (JSONArray) JSON.parse(invoke("condition.getCondition_Muti", getPriceParam).toString());
            if (result.size() > 0) reponsePriceArray.addAll(result);

            getPriceParam.put("SYS_NO_CHECK", "SUPPLIER_ID,COMPANY_ID");
            JSONArray result2 = (JSONArray) JSON.parse(invoke("condition.getCondition_Muti", getPriceParam).toString());
            if (result2.size() > 0) reponsePriceArray.addAll(result2);

            getPriceParam.put("SYS_NO_CHECK", "SUPPLIER_ID");
            JSONArray result3 = (JSONArray) JSON.parse(invoke("condition.getCondition_Muti", getPriceParam).toString());
            if (result3.size() > 0) reponsePriceArray.addAll(result3);

            this.getSPXJDZXB(items, productId, "", upstreamCompanyId, reponsePriceArray);
        }
        return reponsePriceArray;
    }*/

    private JSONArray getPrice(String supplierId, String productId, String upstreamCompanyId, JSONObject items, String method, String companyId) {
        Map getPriceParam = new HashMap();
        getPriceParam.put("SYS_RQ", new Date());
        getPriceParam.put("conditionId", "T03");
        getPriceParam.put("PRODUCT_ID", productId);
        getPriceParam.put("BRAND_ID", items.getString("brandId"));
        getPriceParam.put("CLASSIFY_ID", items.getString("classifyId"));

        JSONArray reponsePriceArray = new JSONArray();
        String commodityInquiryOrderId = items.getString("commodityInquiryOrderId");
        if (StringUtils.hasText(commodityInquiryOrderId) && !"getAllPrice".equals(method)) {
            this.getSPXJDZXB(items, productId, commodityInquiryOrderId, upstreamCompanyId, reponsePriceArray);
        } else {
            getPriceParam.put("SYS_DIM_FIELD", "PRODUCT_ID");
            getPriceParam.put("SYS_NO_CHECK", "SUPPLIER_ID,COMPANY_ID,CAR_LICENSE");
            JSONArray result = (JSONArray) JSON.parse(invoke("condition.getCondition_Muti", getPriceParam).toString());
            if (result.size() > 0) reponsePriceArray.addAll(result);

            JSONObject cloneitem = (JSONObject) items.clone();
            cloneitem.remove("supplier");
            cloneitem.remove("XJDH");
            this.getSPXJDZXB(cloneitem, productId, /*commodityInquiryOrderId*/"", upstreamCompanyId, reponsePriceArray);

            // 区域价格 - 接入商
            this.obtainAccessPrice(productId, companyId, reponsePriceArray);
        }
        return reponsePriceArray;
    }

    private void obtainAccessPrice(String productId, String companyId, JSONArray reponsePriceArray) {
        // 区域价格 - 接入商
        AccessProvider accessProvider =SpringManager.getBean(AccessProviderRepository.class).findByCompany(companyId);
        Map getPriceT04AccessM = new HashMap();
        getPriceT04AccessM.put("SYS_RQ", new Date());
        getPriceT04AccessM.put("conditionId", "T04");
        getPriceT04AccessM.put("PRODUCT_ID", productId);
        getPriceT04AccessM.put("ACCESS_PROVIDER_ID", accessProvider.getId());
        getPriceT04AccessM.put("SYS_DIM_FIELD", "PRODUCT_ID,ACCESS_PROVIDER_ID");
        getPriceT04AccessM.put("SYS_NO_CHECK", "SUPPLIER_ID");
        JSONArray resultAccessArray = (JSONArray) JSON.parse(invoke("condition.getCondition_Muti", getPriceT04AccessM).toString());

        if (!resultAccessArray.isEmpty()) {
            resultAccessArray.forEach(accessPriceSingle -> {((JSONObject) accessPriceSingle).put("COMPANY_ID", companyId);});
            reponsePriceArray.addAll(resultAccessArray);
        }

        // 区域价格 - 公司
        getPriceT04AccessM.remove("ACCESS_PROVIDER_ID");
        getPriceT04AccessM.put("COMPANY_ID", companyId);
        getPriceT04AccessM.replace("SYS_DIM_FIELD", "PRODUCT_ID,COMPANY_ID");
        JSONArray t04CompanyArray = (JSONArray) JSON.parse(invoke("condition.getCondition_Muti", getPriceT04AccessM).toString());
        if (!t04CompanyArray.isEmpty()) reponsePriceArray.addAll(t04CompanyArray);
    }

    /** 询价过来的要货单获取执行表中的价格 */
    private void getSPXJDZXB(JSONObject items, String productId, String commodityInquiryOrderId, String upstreamCompanyId, JSONArray reponsePriceArray) {
        String requireSupplierId = items.getJSONObject("supplier") != null?items.getJSONObject("supplier").getString("id"):"";
        Map condi = new HashMap();
        condi.put("conditionStrategyId", "CG04");
        condi.put("PRODUCT_ID", productId);
        condi.put("SYS_RQ", new Date());
        condi.put("XJDH", commodityInquiryOrderId);
        condi.put("SOURCE", items.getString("source"));
        condi.put("SUPPLIER_ID", requireSupplierId.startsWith("0")?"00" + requireSupplierId:requireSupplierId);
        condi.put("COMPANY_ID", upstreamCompanyId);
        condi.put("CGZID", items.getJSONObject("purchasingGroup") != null?items.getJSONObject("purchasingGroup").getString("id"):"1");
        condi.put("PTID", items.getJSONObject("platform") != null?items.getJSONObject("platform").getString("id"):"1001");
        try {
            Object obj = this.invoke("condition.execConditionStrategy_trans", condi);
            JSONObject priceResult = JSONObject.parseObject(obj.toString());
            if (priceResult.getJSONArray("getSPXJDZXBPrice").size() != 0) {
                JSONArray getSPXJDZXBPrice = priceResult.getJSONArray("getSPXJDZXBPrice");
                getSPXJDZXBPrice.forEach(singlePrice -> {
                    String peiceSupplierId = ((JSONObject) singlePrice).getString("SUPPLIER_IDS");
                    if (peiceSupplierId.length() == 8) {
                        ((JSONObject) singlePrice).put("SUPPLIER_ID", peiceSupplierId.substring(2, peiceSupplierId.length()));
                    } else {
                        ((JSONObject) singlePrice).put("SUPPLIER_ID", peiceSupplierId);
                    }

                });
                reponsePriceArray.addAll(priceResult.getJSONArray("getSPXJDZXBPrice"));
            }
//            String peiceSupplierId = priceResult.getString("SUPPLIER_ID");
//            if (peiceSupplierId.length() == 8) priceResult.put("SUPPLIER_ID", peiceSupplierId.substring(2, peiceSupplierId.length()));
//            reponsePriceArray.add(priceResult);
        } catch (Exception e) {
            e.getMessage();
        }
    }

    /** 生成采购订单 */
    public JSONArray insertPurchaseOrder(SimpleRequest request) {
        JSONObject getJO = request.getJO();
        String note = getJO.get("note") == null?"":getJO.getString("note");
        JSONArray purchaseRequireItems = getJO.getJSONArray("purchaseRequireItems");
        this.judgeProductState(purchaseRequireItems); // 判断商品状态

        // 分组
        JSONArray filterPurchaseRequireItems = purchaseRequireItems.stream().filter(item -> ((JSONObject) item).getBooleanValue("checkData")).collect(Collectors.toCollection(JSONArray::new));
        if (filterPurchaseRequireItems.size() == 0) throw new RuntimeException("请勾选数据！");
        //向第三方要货
        filterPurchaseRequireItems = new JSONArray(thirdParty(filterPurchaseRequireItems));

        Map<Object, List<Object>> groupPurchaseRequireItem = filterPurchaseRequireItems.stream().collect(
            Collectors.groupingBy(item -> {
                JSONObject itemObj = (JSONObject) item;
                JSONObject key = new JSONObject();
                this.groupItem(key, itemObj);
                return key;
            })
        );

        // 循环拼接采购信息
        AtomicDouble purchaseQty = new AtomicDouble(0);
        Map carrierInfoCache = new HashMap();
        groupPurchaseRequireItem.forEach((k, v) -> {
            PurchaseOrder purchaseOrder = new PurchaseOrder();
            List<PurchaseOrderItem> orderItemSet = new ArrayList<>();
            this.appendPurchasOrder(purchaseOrder, (JSONObject) k, request.getPersonId(), note);
            Map storageRequireItemId = new HashMap<>();
            v.stream().forEach(requireItem-> {
                JSONObject requireItemObj = (JSONObject) requireItem;
                if (requireItemObj.getBooleanValue("checkData") && requireItemObj.getDoubleValue("distributionQty") != 0) {
                    String productId = requireItemObj.getJSONObject("product").getString("id");
                    String supplierId = requireItemObj.getJSONObject("supplier").getString("id");
                    appendPurchaseOrderItem(purchaseOrder, orderItemSet, requireItemObj);
                    storageRequireItemId.put(productId, requireItemObj.getString("id"));
                    if (carrierInfoCache.get(supplierId) == null) {
                        List<Map> findCarriers = SpringManager.getBean(ServicePlanItemRepository.class).findCarrier(requireItemObj.getString("commodityInquiryOrderId"), productId, requireItemObj.getString("source"));
                        if (!findCarriers.isEmpty()) {
                            carrierInfoCache.put(supplierId, findCarriers.get(0));
                        }
                    }
                }
            });
            if (orderItemSet.size() != 0) {
                purchaseQty.set(purchaseQty.get() + 1);
                if (purchaseOrder.getSupplier() == null) throw new RuntimeException("没有供应商, 请检查数据!");
                purchaseOrder.setPurchaseItems(orderItemSet);
                boolean pushSingleCalendar = supplierBusinessScopeService.judgeInstallSupplier(purchaseOrder.getSupplier().getId());
                if (pushSingleCalendar) { // 供应商相关功能未移植到新框架时, 采购订单推单的先同步到老框架
                    Map<Object, List<Object>> groupPurchaseOrder = purchaseOrder.getPurchaseItems().stream().collect(
                        Collectors.groupingBy(item -> {
                            return ((PurchaseOrderItem) item).getSourceState().getId();
                        })
                    );
                    groupPurchaseOrder.forEach((k1, v1) -> {
                        JSONArray cgddArray = new JSONArray();
                        JSONObject cgddObj = new JSONObject();
                        cgddObj.put("CPHM", ((JSONObject) k).get("carLicense"));
                        cgddObj.put("UUID", getJO.getString("UUID"));
                        cgddObj.put("PTID", ((JSONObject) k).get("platformId"));
                        this.appendCGDD(purchaseOrder, cgddObj, note);
                        this.appendCGDDMX(purchaseOrder, k1.toString(), cgddArray, storageRequireItemId);
                        cgddObj.put("PUR_CGDDMX", cgddArray);
                        if (carrierInfoCache.get(purchaseOrder.getSupplier().getId()) != null) {
                            cgddObj.put("PSFS", ((Map)carrierInfoCache.get(purchaseOrder.getSupplier().getId())).get("CARRIER_NAME"));
                        }
                        outboxSubscriberService.commonSendRequest("local:ReplenishmentManagementService.synCGDD", "synCGDD Error ! " + purchaseOrder.getProductRequire(), cgddObj);
                    });
                } else {
                    PurchaseOrder newPurchaseOrder = invoke("purchase.order.create", MapUtil.mapped(purchaseOrder));

                    // 写要货订货数量
//                    this.updateRequireItemOrderQty(newPurchaseOrder.getPurchaseItems());
                }

            }
            if (purchaseQty.get() == 0) throw new RuntimeException("未获取到有效数据！请检查是否填写采购数量");
        });

        // 最后判断勾选的是否全部采购完毕，未采购完毕的返回前端
        return this.judgePurchaseNoReplenished(getJO.getJSONArray("purchaseRequireItems"));
    }

    /**
     * 向第三方供应商采购
     * @param purchaseRequireItems
     * @return
     */
    private List thirdParty(JSONArray purchaseRequireItems){
        List list = sendSynEvent("event:purchase.order.thirdParty", MapUtil.mapper("item", purchaseRequireItems));
        if (list.isEmpty())return purchaseRequireItems;
        //返回不是第三方的要货单并且未询价
        return purchaseRequireItems.stream().filter(item -> {
            JSONObject param = (JSONObject) item;
            ProductRequire productRequire = productRequireRepository.findOne(param.getString("productRequireId"));
            ProductRequireItem productRequireItem = productRequire.getProductRequireItems().stream().findAny().get();
            return !(param.getString("supplier").contains("006989") && StringUtils.hasText(productRequireItem.getCommodityInquiryOrderId()));//测试库：006570, 正式库：006989
        }).collect(Collectors.toList());
    }

    // 判断商品导入是否为停用
    private void judgeProductState(JSONArray purchaseRequireItems) {
        Pattern p;
        Matcher m;
        String productIdStr = "";
        List errorProductIds = new ArrayList<>();
        for (int i = 0; i < purchaseRequireItems.size(); i++) {
            productIdStr += "'" + purchaseRequireItems.getJSONObject(i).getJSONObject("product").getString("id") + "',";
            double number = i / 1000;
            p = Pattern.compile("[1-9]*");
            m = p.matcher("" + number);
            if (m.matches() || i == purchaseRequireItems.size() - 1) {
                errorProductIds.addAll(productRepository.findAll("SELECT ID FROM MAS_PRODUCT WHERE ID IN (" + productIdStr.substring(0, productIdStr.length() - 1) + ") AND (STATE = '2' OR STATE = '3') "));
                productIdStr = "";
            }
        }
        if (errorProductIds.size() > 0) {
            throw new RuntimeException("停产下市、停用商品不可导入，请找替换产品采购！商品有" + errorProductIds.toString());
        }
    }

    /** 生成采购订单明细分组 */
    private void groupItem(JSONObject key, JSONObject itemObj) {
        if (itemObj.getJSONObject("supplier") == null) throw new RuntimeException("已勾选的数据供应商不能为空!!");
        if (itemObj.getJSONObject("company") == null) throw new RuntimeException("已勾选的数据公司不能为空!!");
        if (itemObj.getJSONObject("dept") == null) throw new RuntimeException("已勾选的数据部门不能为空!!");
        if (itemObj.getJSONObject("contract") == null) throw new RuntimeException("已勾选的数据合同不能为空!!");
        key.put("companyId", itemObj.getJSONObject("company").getString("id"));
        key.put("supplierId", itemObj.getJSONObject("supplier").getString("id"));
        key.put("deptId", itemObj.getJSONObject("dept").getString("id"));
        key.put("contractId", itemObj.getJSONObject("contract").getString("id"));
        key.put("locationId", itemObj.getJSONObject("location").getString("id"));
        key.put("platformId", itemObj.getJSONObject("platform").getString("id"));
        key.put("productRequireId", itemObj.getString("productRequireId"));
        key.put("carLicense", itemObj.getJSONObject("customerExpand") == null?"":itemObj.getJSONObject("customerExpand").getString("carLicense"));
        try {
            key.put("siteId", itemObj.getJSONArray("site") == null?"":itemObj.getJSONArray("site").getJSONObject(0).getString("id"));
        } catch (Exception e) {
            key.put("siteId", itemObj.getJSONObject("site") == null?"":itemObj.getJSONObject("site").getString("id"));
        }

        try {
            key.put("purchasingGroupId", itemObj.getJSONArray("purchasingGroup") == null?"":itemObj.getJSONArray("purchasingGroup").getJSONObject(0).getString("id"));
        } catch (Exception e) {
            key.put("purchasingGroupId", itemObj.getJSONObject("purchasingGroup") == null?"":itemObj.getJSONObject("purchasingGroup").getString("id"));
        }
        if (StringUtils.isEmpty(key.getString("purchasingGroupId"))) throw new RuntimeException("已勾选的数据【采购组】不能为空!!");
    }

    /** 采购后剩余数据返回 */
    private JSONArray judgePurchaseNoReplenished(JSONArray purchaseRequireItems) {
        JSONArray returnData = new JSONArray();
        purchaseRequireItems.forEach(items -> {
            JSONObject itemObj = (JSONObject) items;
            double toBeReplenishedQty = itemObj.getDoubleValue("toBeReplenishedQty");
            double distributionQty = itemObj.getDoubleValue("distributionQty");
            double remainingQty = toBeReplenishedQty - distributionQty;
            if (remainingQty > 0) {
                itemObj.put("toBeReplenishedQty", remainingQty);
                itemObj.put("distributionQty", remainingQty);
                returnData.add(itemObj);
            }
        });
        return returnData;
    }


    /** 外部操作修改要货订货数量
     * 采购订单审核
     * 删除
     * */
    public void externalUpdateRequireItemOrderQty(SimpleRequest request) {
        PurchaseOrder purchaseOrder = request.getO(PurchaseOrder.class);

        if (!"confirmed".equals(purchaseOrder.getState()) && !"delete".equals(purchaseOrder.getState())) return;

        // 增加供应商的收货回写
        if (Objects.nonNull(purchaseOrder.getSupplierType()) && "santou".equals(purchaseOrder.getSupplierType())) {
            thirdPartyOrder.thirdPartyUpdateRequireQty(purchaseOrder);
            return;
        }

        if (!"要货补货管理-采购".equals(purchaseOrder.getNote()) && !"要货自动补货-采购".equals(purchaseOrder.getNote())) return;
        this.updateRequireItemOrderQty(purchaseOrder.getPurchaseItems());
    }

    /** 修改要货订货数量 */
    private void updateRequireItemOrderQty(List<PurchaseOrderItem> purchaseOrderItemSet) {
        purchaseOrderItemSet.forEach(purchaseOrderItem -> {
            if (StringUtils.hasText(purchaseOrderItem.getSourceItemId())) return;
            String state = purchaseOrderItem.getPurchaseOrder().getState();
            double qty = 0;
            if (state.equals("sent")) qty = purchaseOrderItem.getProductUomQty();
            if (state.equals("delete") || state.equals("confirmed")) {
                double demandQty = purchaseOrderItem.getDemandQty();
                double productUomQty = purchaseOrderItem.getProductUomQty();
                double newQty = demandQty > productUomQty?demandQty:productUomQty;
                qty = -1 * newQty;
            }
            String requireId = purchaseOrderItem.getPurchaseOrder().getProductRequire();
            String productId = purchaseOrderItem.getProduct().getId();
            ProductRequire require = /*productRequireService.updateRequireQty(requireId, "", productId, qty, 0, 0)*/ null; // 弃用
            SpringManager.getBean(ProductRequireRepository.class).save(require);
        });
    }

    /** 采购订单审核写要货已分配数量、要货扩展信息*/
    public void externalRequireExpand(SimpleRequest request) {
        PurchaseOrder purchaseOrder = request.getO(PurchaseOrder.class);
        String state = purchaseOrder.getState();
        if ("santou".equals(purchaseOrder.getSupplierType()) || "supplier".equals(purchaseOrder.getSupplierType())) return;

        if (!(("confirmed".equals(state) || "cancel".equals(state)) && !StringUtils.isEmpty(purchaseOrder.getProductRequire()))) return;
        if ("confirmed".equals(state)) {
            purchaseOrder.getPurchaseItems().forEach(purchaseOrderItem -> {
                if (StringUtils.hasText(purchaseOrderItem.getSourceItemId())) return;
//                autoProductRequireDumpService.judgeOfflineDump(purchaseOrder.getId(), purchaseOrder.getProductRequire(), purchaseOrderItem.getProduct(), purchaseOrderItem.getUom(), purchaseOrderItem.getProductUomQty());
            });
        } else if ("cancel".equals(state)) {
            purchaseOrder.getPurchaseItems().forEach(orderItem -> {
                if (StringUtils.hasText(orderItem.getSourceItemId())) return;
//                autoProductRequireDumpService.dumpDealWithQty(purchaseOrder.getId(), orderItem.getStopQty() - orderItem.getQtyReceived(), orderItem.getProduct().getId(), orderItem.getUom().getId(), 0, 0);
            });
            purchaseService.cacenlProductRequire(purchaseOrder);
        }

    }

    /** 【交货单】收货修改要货扩展表及要货数量 */
/*    public void pickUpdateRequireExpandAndRequireQty(SimpleRequest request) {
        Pick pick = request.getO(Pick.class);
        if (!pick.getOperation().equals("receipt") || pick.getState().equals("cancel")) return;
        PurchaseOrder purchaseOrder = SpringManager.getBean(PurchaseOrderRepository.class).findOne(pick.getOrigin());
        if (purchaseOrder == null || !"要货补货管理-采购".equals(purchaseOrder.getNote())) return;
        pick.getPickItems().forEach(pickItem -> {
            List requireItemIds = sendSynEvent("event:scm.purchaseService.accordItemIdFindSourceItemId", MapUtil.mapper("id", pickItem.getOriginLine()));
            if (!requireItemIds.isEmpty()) return;

            String productId = pickItem.getProduct().getId();
            ProductUom purchaseUom = productUomRepository.findAll(JpaDsl.toCriteriaByEq("purchaseFirst", true, "uomCategory.id", productId)).get(0);
            autoProductRequireDumpService.dumpDealWithQty(pick.getOrigin(), 0, productId, purchaseUom.getId(), pickItem.getQtyDone(), 0);
        });
    }*/

    /** 拼接要货管理查找-待补货明细数据 */
    private void appendProductRequireItes(ProductRequireItem requireItem, List returnData) {
        Map requireItemMap = new HashMap();
        requireItemMap.put("toBeReplenishedQty", 0);
        requireItemMap.put("id", requireItem.getId());

        requireItemMap.put("product", getModelData(requireItem.getProduct(), Arrays.asList("id", "name")));
        requireItemMap.put("commodityInquiryOrderId", requireItem.getCommodityInquiryOrderId());
        requireItemMap.put("uom", MapUtil.mapper("id", requireItem.getUom().getId(), "name", requireItem.getUom().getName(), "factor", requireItem.getUom().getFactor()));
        requireItemMap.put("qtyRequire", requireItem.getQtyRequire());
        requireItemMap.put("qtyAssigned", requireItem.getQtyAssigned());
        requireItemMap.put("qtyEnded", requireItem.getQtyEnded());
        requireItemMap.put("orderQty", requireItem.getOrderQty());
        if (requireItem.getProductRequire().getCustomerExpand() != null) {
            requireItemMap.put("customerExpand", MapUtil.mapper("id", requireItem.getProductRequire().getCustomerExpand().getId(), "carLicense", requireItem.getProductRequire().getCustomerExpand().getCarLicense()));
        }
        requireItemMap.put("productRequireId", requireItem.getProductRequire().getId());
        requireItemMap.put("source", requireItem.getProductRequire().getSource());
        requireItemMap.put("location", MapUtil.mapper("id", requireItem.getProductRequire().getLocation().getId(), "name", requireItem.getProductRequire().getLocation().getName(),
                "company", MapUtil.mapper("id", requireItem.getProductRequire().getLocation().getCompany().getId())));
        requireItemMap.put("platform", MapUtil.mapper("id", requireItem.getProductRequire().getPlatform().getId(), "name", requireItem.getProductRequire().getPlatform().getName()));
        if (requireItem.getSupplier() != null) requireItemMap.put("supplier", MapUtil.mapper("id", requireItem.getSupplier().getId(), "name", requireItem.getSupplier().getName()));
        if (requireItem.getSite() != null) requireItemMap.put("site", MapUtil.mapper("id", requireItem.getSite().getId(), "name", requireItem.getSite().getName()));
        if (requireItem.getPurchasingGroup() != null) requireItemMap.put("purchasingGroup", MapUtil.mapper("id", requireItem.getPurchasingGroup().getId(), "name", requireItem.getPurchasingGroup().getName()));
        requireItemMap.put("classifyId", requireItem.getProduct().getClassify().getId());
        requireItemMap.put("brandId", requireItem.getProduct().getBrand().getId());
        requireItemMap.put("requireLocationCompanyId", requireItem.getProductRequire().getLocation().getCompany().getId());
        requireItemMap.put("requireLocationCompanyName", requireItem.getProductRequire().getLocation().getCompany().getName());
        requireItemMap.put("expectedArrivalTime", requireItem.getExpectedArrivalTime());
        System.out.println("-----------------------" + requireItem.getProductRequire().getId());
        if (!"materiel".equals(requireItem.getProductRequire().getSourceBusinessType())) {
            System.out.println(requireItem.getProductRequire().getId() + "--------------------");
            requireItemMap.put("sourceStateId", requireItem.getSourceState().getId());
            requireItemMap.put("sourceStateCode", requireItem.getSourceState().getCode());
        }

        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (requireItem.getProductRequire().getApproveDate() != null) requireItemMap.put("approveDate", fmt.format(requireItem.getProductRequire().getApproveDate()));
        returnData.add(requireItemMap);
    }

    private Map getModelData(Object obj, List<String> fieldList){
        Map map = new HashMap();
        fieldList.forEach( filed -> {
            map.put(filed,  ReflectUtil.getFieldValue(obj, filed));
        });
        return map;
    }

    /** 拼接采购 - 待补货明细返回 */
    /*private void appendReturnPurchaseRequireItem(JSONObject requireItemObj, JSONObject newPurchaseRequireItems) {
        // 获取合同、供应商
        String productId = requireItemObj.getJSONObject("product").getString("id");
        String commodityInquirySupplierId = requireItemObj.getJSONObject("supplier") == null?"":requireItemObj.getJSONObject("supplier").getString("id");
        Location requireLocation = locationRepository.findOne(requireItemObj.getJSONObject("location").getString("id"));
        ProductUom purchaseUom = productUomRepository.findAll(JpaDsl.toCriteriaByEq("purchaseFirst", true, "uomCategory.id", productId)).get(0);
        ProductUom minFactorUom = productUomRepository.findAll(JpaDsl.toCriteriaByEq("factor", 1, "uomCategory.id", productId)).get(0);

        List supplierIds = new ArrayList();
        supplierIds.add(commodityInquirySupplierId);
        List<Contract> contractList = this.getSupplierContract(requireLocation.getCompany().getId(), supplierIds,"", new ArrayList());

        double toBeReplenishedQty = requireItemObj.getDoubleValue("qtyRequire") - requireItemObj.getDoubleValue("qtyAssigned") - requireItemObj.getDoubleValue("qtyEnded") - requireItemObj.getDoubleValue("orderQty");
        newPurchaseRequireItems.put("toBeReplenishedQty", toBeReplenishedQty);
        contractList.stream().anyMatch(contract -> {
            String supplierId = contract.getPartner().getId();
            // 获取价格
            JSONArray priceArray = this.getPrice(supplierId, productId, contract.getCompany().getId(), requireItemObj*//*.getString("commodityInquiryOrderId")*//*, "appendReturnPurchaseRequireItem");
            JSONObject priceObj = (JSONObject) priceArray.stream().filter(singlePrice -> {
               return ((JSONObject) singlePrice).getDoubleValue("P001") > 0 && contract.getPartner().getId().equals(((JSONObject) singlePrice).getString("SUPPLIER_ID"));
            }).findFirst().orElse(new JSONObject());
            newPurchaseRequireItems.put("P001", priceObj.get("P001"));
            if (newPurchaseRequireItems.getDoubleValue("P001") > 0 && StringUtils.hasText(commodityInquirySupplierId) && supplierId.equals(commodityInquirySupplierId)) {
                String contractCompanyId = contract.getCompany().getId();
                boolean isPlatForm = "1007".equals(contractCompanyId);
                String companyId = isPlatForm?requireLocation.getCompany().getId():contract.getCompany().getId();
                Dept dept = isPlatForm?deptRepository.findAll(JpaDsl.toCriteriaByEq("company.id", companyId, "deptType.id", "000006")).get(0):contract.getDept();
//                PartyRole company = partyRoleRepository.findOne(companyId);
                double toBeReplenishedQty2 = newPurchaseRequireItems.getDoubleValue("toBeReplenishedQty");
                newPurchaseRequireItems.put("contract", *//*contract*//*MapUtil.mapper("id", contract.getId(), "name", contract.getName()));
                newPurchaseRequireItems.put("dept", *//*dept*//*MapUtil.mapper("id", dept.getId(), "name", dept.getName()));
                newPurchaseRequireItems.put("supplier", *//*contract.getPartner()*//*MapUtil.mapper("id", contract.getPartner().getId(), "name", contract.getPartner().getName()));
                newPurchaseRequireItems.put("company", MapUtil.mapper("id", dept.getCompany().getId(), "name", dept.getCompany().getName())); // mapping 的时候数据不对，特殊处理
                newPurchaseRequireItems.put("distributionQty", toBeReplenishedQty2);
                newPurchaseRequireItems.put("contractCompany", *//*contract.getCompany()*//*MapUtil.mapper("id", contract.getCompany().getId(), "name", contract.getCompany().getName()));

                // 获取税率
                this.getTax(supplierId, productId, newPurchaseRequireItems);
                double P001 = newPurchaseRequireItems.getDoubleValue("P001");
                P001 = getUnP001(P001, priceObj.getDoubleValue("P101"), isPlatForm, priceObj.getString("XJBJ"));
                newPurchaseRequireItems.put("P001", minFactorUom.computePrice(P001, purchaseUom));
                newPurchaseRequireItems.put("amount", toBeReplenishedQty2 * newPurchaseRequireItems.getDoubleValue("P001"));
                double P902 = priceObj.getDoubleValue("P902");
                if (priceObj.getDoubleValue("P902") == 0) {
                    JSONObject getCeilPrice = purchaseService.getPurcherPrice(contractCompanyId, contract.getPartner().getId(), productId, "");
                    P902 = getCeilPrice.getDoubleValue("P902");
                }
                newPurchaseRequireItems.put("priceCeiling", minFactorUom.computePrice(P902, purchaseUom));
                return true;
            } else {
                newPurchaseRequireItems.put("amount", 0);
                newPurchaseRequireItems.put("distributionQty", 0);
            }

            return false;
        });

        if (newPurchaseRequireItems.getJSONObject("supplier") == null && requireItemObj.getJSONObject("supplier") != null) newPurchaseRequireItems.put("supplier", requireItemObj.getJSONObject("supplier"));
        newPurchaseRequireItems.put("commodityInquiryOrderId", requireItemObj.get("commodityInquiryOrderId"));
        newPurchaseRequireItems.put("purchaseUom", MapUtil.mapper("id", purchaseUom.getId(), "name", purchaseUom.getName()));
        newPurchaseRequireItems.put("platform", MapUtil.mapper("id", requireItemObj.getJSONObject("platform").getString("id"), "name", requireItemObj.getJSONObject("platform").getString("name")));
        newPurchaseRequireItems.put("product", requireItemObj.getJSONObject("product"));
        newPurchaseRequireItems.put("location", requireItemObj.getJSONObject("location"));
        newPurchaseRequireItems.put("checkData", requireItemObj.getBooleanValue("checkData"));
        newPurchaseRequireItems.put("productRequireId", requireItemObj.getString("productRequireId"));
        newPurchaseRequireItems.put("requireUom", requireItemObj.getJSONObject("uom"));
        newPurchaseRequireItems.put("id", requireItemObj.getString("id"));
        newPurchaseRequireItems.put("site", requireItemObj.getJSONObject("site"));
        if (requireItemObj.getJSONObject("site") != null) {
            JSONObject site = requireItemObj.getJSONObject("site");
            newPurchaseRequireItems.put("site", MapUtil.mapper("id", site.getString("id"), "name", site.getString("name")));
        }
        if (requireItemObj.getJSONObject("purchasingGroup") != null) {
            JSONObject purchasingGroup = requireItemObj.getJSONObject("purchasingGroup");
            newPurchaseRequireItems.put("purchasingGroup", MapUtil.mapper("id", purchasingGroup.getString("id"), "name", purchasingGroup.getString("name")));
        }
        JSONObject customerExpand = requireItemObj.getJSONObject("customerExpand");
        if (requireItemObj.getJSONObject("customerExpand") != null) {
            newPurchaseRequireItems.put("customerExpand", MapUtil.mapper("id", customerExpand.getString("id"), "carLicense", customerExpand.getString("carLicense")));
        }
    }*/

    private JSONObject appendReturnPurchaseRequireItem(JSONObject requireItemObj) {
        String productId = requireItemObj.getJSONObject("product").getString("id");
        String platformId = requireItemObj.getJSONObject("platform").getString("id");
        String originMethod = requireItemObj.getString("originMethod");
        String locationCompanyId = requireItemObj.getJSONObject("location").getJSONObject("company").getString("id");
        ProductUom purchaseUom = productUomRepository.findAll(JpaDsl.toCriteriaByEq("purchaseFirst", true, "uomCategory.id", productId)).get(0);
        ProductUom minFactorUom = productUomRepository.findAll(JpaDsl.toCriteriaByEq("factor", 1, "uomCategory.id", productId)).get(0);
        JSONArray priceArray = getPrice("", productId, "", requireItemObj, "appendReturnPurchaseRequireItem", locationCompanyId);
        List supplierIds = getPriceSupplier(priceArray);
        supplierIds.add("占位");
        List<Contract> contractList = this.getContract(requireItemObj.getString("requireLocationCompanyId"), supplierIds);
        double toBeReplenishedQty = requireItemObj.getDoubleValue("qtyRequire") - requireItemObj.getDoubleValue("qtyAssigned") - requireItemObj.getDoubleValue("qtyEnded") - requireItemObj.getDoubleValue("orderQty");

        JSONObject newPurchaseRequireItems = new JSONObject();
        this.appendReturnPurchaseRequireData(newPurchaseRequireItems, requireItemObj, purchaseUom);
        newPurchaseRequireItems.put("toBeReplenishedQty", toBeReplenishedQty);
        newPurchaseRequireItems.put("source", requireItemObj.getString("source"));
        contractList.stream().anyMatch(contract -> {
            String contractType = contract.getContractType().getId();
            priceArray.stream().anyMatch(singlePrice -> {
                JSONObject singlePriceObj = (JSONObject) singlePrice;
                String  companyId = singlePriceObj.getString("COMPANY_ID");
                String  supplierId = singlePriceObj.getString("SUPPLIER_ID");
                double  eP001 = singlePriceObj.getDoubleValue("P001");
                if (StringUtils.isEmpty(companyId) || contractType.equals("Contract.contractType.platform") || (!StringUtils.isEmpty(companyId) && companyId.equals(contract.getCompany().getId()) && !contractType.equals("Contract.contractType.platform"))) {
                    if (supplierId.equals(contract.getPartner().getId()) && eP001 > 0) {
                        if (StringUtils.hasText(originMethod) && "createPurchaseNewAndOld".equals(originMethod) && "1007".equals(platformId) && "Contract.contractType.platform".equals(contract.getContractType().getId())) {
                            this.appendReturnPurchaseRequirePriceData(requireItemObj, newPurchaseRequireItems, singlePriceObj, contract, minFactorUom, purchaseUom);
                            return true;
                        } else if (StringUtils.hasText(originMethod) && "createPurchaseNewAndOld".equals(originMethod) && !"1007".equals(platformId) && "Contract.contractType.supplier".equals(contract.getContractType().getId())){
                            this.appendReturnPurchaseRequirePriceData(requireItemObj, newPurchaseRequireItems, singlePriceObj, contract, minFactorUom, purchaseUom);
                            return true;
                        } else {
                            this.appendReturnPurchaseRequirePriceData(requireItemObj, newPurchaseRequireItems, singlePriceObj, contract, minFactorUom, purchaseUom);
                            return true;
                        }
                    }
                }
                return false;
            });
            if (newPurchaseRequireItems.getJSONObject("contract") != null) return true;
            return false;
        });
        return newPurchaseRequireItems;
    }

    // 拼接【采购】价格等信息返回
    private void appendReturnPurchaseRequirePriceData(JSONObject requireItemObj, JSONObject newPurchaseRequireItems, JSONObject singlePriceObj, Contract contract, ProductUom minFactorUom, ProductUom purchaseUom) {
        String productId = newPurchaseRequireItems.getJSONObject("product").getString("id");
        // mapping 防止数据不对， 内存溢出
        newPurchaseRequireItems.put("P001", singlePriceObj.getDoubleValue("P001"));
        newPurchaseRequireItems.put("contract", MapUtil.mapper("id", contract.getId(), "name", contract.getName()));
//        newPurchaseRequireItems.put("dept", MapUtil.mapper("id", contract.getDept().getId(), "name", contract.getDept().getName()));
        newPurchaseRequireItems.put("supplier", MapUtil.mapper("id", contract.getPartner().getId(), "name", contract.getPartner().getName()));
        newPurchaseRequireItems.put("distributionQty", newPurchaseRequireItems.getDoubleValue("toBeReplenishedQty"));
        newPurchaseRequireItems.put("expectedArrivalTime", newPurchaseRequireItems.getDoubleValue("expectedArrivalTime"));
        String locationCompanyId = requireItemObj.getString("requireLocationCompanyId");
        String operation = invoke("purchase.order.getModel", MapUtil.mapper("companyId", locationCompanyId));
        String contranctCompanyId = contract.getCompany().getId();
        if ("1007".equals(contranctCompanyId)/*"empower".equals(operation)*/) {
//            String locationCompanyName = currentData.getJSONObject("location").getJSONObject("company").getString("name");
            newPurchaseRequireItems.put("dept", deptRepository.findAll(JpaDsl.toCriteriaByEq("company.id", locationCompanyId, "deptType.id", "000006")).get(0));
            newPurchaseRequireItems.put("company", MapUtil.mapper("id", locationCompanyId, "name", requireItemObj.getString("requireLocationCompanyName")));
        } else {
            newPurchaseRequireItems.put("company", MapUtil.mapper("id", contract.getCompany().getId(), "name", contract.getCompany().getName()));
            newPurchaseRequireItems.put("dept", MapUtil.mapper("id", contract.getDept().getId(), "name", contract.getDept().getName()));
        }

       /* if ("1007".equals(contranctCompanyId)) {
            newPurchaseRequireItems.put("company", MapUtil.mapper("id", requireItemObj.getString("requireLocationCompanyId"), "name", requireItemObj.getString("requireLocationCompanyName")));
        } else {
            newPurchaseRequireItems.put("company", MapUtil.mapper("id", contranctCompanyId, "name", contract.getCompany().getName()));
        }*/
        newPurchaseRequireItems.put("contractCompany", MapUtil.mapper("id", contranctCompanyId, "name", contract.getCompany().getName()));
        // 获取税率
        this.getTax(newPurchaseRequireItems.getJSONObject("company").getString("id"), contract.getPartner().getId(), productId, newPurchaseRequireItems);
        double P001 = newPurchaseRequireItems.getDoubleValue("P001");
        P001 = getUnP001(P001, singlePriceObj.getDoubleValue("P101"), "1007".equals(contract.getCompany().getId()), singlePriceObj.getString("XJBJ"));
        newPurchaseRequireItems.put("P001", minFactorUom.computePrice(P001, purchaseUom));
        newPurchaseRequireItems.put("amount", newPurchaseRequireItems.getDoubleValue("toBeReplenishedQty") * newPurchaseRequireItems.getDoubleValue("P001"));
        double P902 = singlePriceObj.getDoubleValue("P902");
        if (singlePriceObj.getDoubleValue("P902") == 0) { // 不应该取二遍
            JSONObject getCeilPrice = purchaseService.getPurcherPrice(contract.getCompany().getId(), contract.getPartner().getId(), productId, "");
            P902 = getCeilPrice.getDoubleValue("P902");
        }
        newPurchaseRequireItems.put("priceCeiling", minFactorUom.computePrice(P902, purchaseUom));
    }

    // 拼接【采购】默认带过来的数据
    private void appendReturnPurchaseRequireData(JSONObject newPurchaseRequireItems, JSONObject requireItemObj, ProductUom purchaseUom) {
        if (newPurchaseRequireItems.getJSONObject("supplier") == null && requireItemObj.getJSONObject("supplier") != null) newPurchaseRequireItems.put("supplier", requireItemObj.getJSONObject("supplier"));
        newPurchaseRequireItems.put("commodityInquiryOrderId", requireItemObj.get("commodityInquiryOrderId"));
        newPurchaseRequireItems.put("purchaseUom", MapUtil.mapper("id", purchaseUom.getId(), "name", purchaseUom.getName()));
        newPurchaseRequireItems.put("platform", MapUtil.mapper("id", requireItemObj.getJSONObject("platform").getString("id"), "name", requireItemObj.getJSONObject("platform").getString("name")));
        newPurchaseRequireItems.put("product", requireItemObj.getJSONObject("product"));
        newPurchaseRequireItems.put("location", requireItemObj.getJSONObject("location"));
        newPurchaseRequireItems.put("checkData", requireItemObj.getBooleanValue("checkData"));
        newPurchaseRequireItems.put("productRequireId", requireItemObj.getString("productRequireId"));
        newPurchaseRequireItems.put("requireUom", requireItemObj.getJSONObject("uom"));
        newPurchaseRequireItems.put("id", requireItemObj.getString("id"));
        newPurchaseRequireItems.put("site", requireItemObj.getJSONObject("site"));
        newPurchaseRequireItems.put("expectedArrivalTime", requireItemObj.getDouble("expectedArrivalTime"));
        newPurchaseRequireItems.put("sourceStateId", requireItemObj.getString("sourceStateId"));
        newPurchaseRequireItems.put("sourceStateCode", requireItemObj.getString("sourceStateCode"));
        if (requireItemObj.getJSONObject("site") != null) {
            JSONObject site = requireItemObj.getJSONObject("site");
            newPurchaseRequireItems.put("site", MapUtil.mapper("id", site.getString("id"), "name", site.getString("name")));
        }
        if (requireItemObj.getJSONObject("purchasingGroup") != null) {
            JSONObject purchasingGroup = requireItemObj.getJSONObject("purchasingGroup");
            newPurchaseRequireItems.put("purchasingGroup", MapUtil.mapper("id", purchasingGroup.getString("id"), "name", purchasingGroup.getString("name")));
        }
        JSONObject customerExpand = requireItemObj.getJSONObject("customerExpand");
        if (requireItemObj.getJSONObject("customerExpand") != null) {
            newPurchaseRequireItems.put("customerExpand", MapUtil.mapper("id", customerExpand.getString("id"), "carLicense", customerExpand.getString("carLicense")));
        }
    }

    private List<Contract> getContract(String companyId, List supplierId) {
        List<Contract> contracts = new ArrayList<>();
        List<Contract> contractList = new ArrayList<>();
        List companys = new ArrayList();
        List businessCompanys = new ArrayList();
        businessCompanys.add(companyId);
        companys.add(companyId);
        // 查找赋能合同
        List<FnContract> fnContractList = fnContractRepository.qryValidFnContract(companyId);
        if (fnContractList.size() != 0) {
            String fnCompanyId = fnContractList.get(0).getCompany().getId();
            companys.add(fnCompanyId);
            contractList = contractRepository.accordingSupplierQuery(companys, "Contract.contractType.platform", supplierId);
            if (contractList.size() > 0) {
                contracts.addAll(contractList);
            }
//            companyId = fnCompanyId;
        }

        // 根据对照表找采购合同
        List<BusinessParam> businessParams = businessParamRepository.accordingToCompanyContract(companys);
        businessParams.forEach(singleBusiness -> businessCompanys.add(singleBusiness.getValue()));
//        if (businessParams.size() > 0) companyId = businessParams.get(0).getValue();
        if (fnContractList.size() != 0) {
            List<Contract> purchaseContracts = new ArrayList<>();
            purchaseContracts = contractRepository.qryValidContract(businessCompanys, "Contract.contractType.supplier", supplierId);
            if (purchaseContracts.size() != 0) contracts.addAll(purchaseContracts);
        } else {
            contracts.addAll(contractRepository.accordingSupplierQuery(businessCompanys, "Contract.contractType.supplier", supplierId));
        }
        return contracts;
    }

    public List<Contract> getContract(SimpleRequest simpleRequest){
        JSONObject jo = simpleRequest.getJO();
        String companyId = jo.getString("companyId");
        List supplierIds = jo.get("supplierId")!=null?jo.getJSONArray("supplierId"):new JSONArray();
        List<Contract> contracts = new ArrayList<>();
        List<Contract> contractList = new ArrayList<>();
        List companys = new ArrayList();
        List businessCompanys = new ArrayList();
        businessCompanys.add(companyId);
        companys.add(companyId);
        // 查找赋能合同
        List<FnContract> fnContractList = fnContractRepository.qryValidFnContract(companyId);
        if (fnContractList.size() != 0) {
            String fnCompanyId = fnContractList.get(0).getCompany().getId();
            companys.add(fnCompanyId);
            contractList =supplierIds.isEmpty()? contractRepository.accordingSupplierQuery(companys, "Contract.contractType.platform"):
                                                contractRepository.accordingSupplierQuery(companys, "Contract.contractType.platform",supplierIds);
            if (contractList.size() > 0) {
                contracts.addAll(contractList);
            }
//            companyId = fnCompanyId;
        }

        // 根据对照表找采购合同
        List<BusinessParam> businessParams = businessParamRepository.accordingToCompanyContract(companys);
        businessParams.forEach(singleBusiness -> businessCompanys.add(singleBusiness.getValue()));
//        if (businessParams.size() > 0) companyId = businessParams.get(0).getValue();
        if (fnContractList.size() != 0) {
            List<Contract> purchaseContracts = new ArrayList<>();
            purchaseContracts = supplierIds.isEmpty()? contractRepository.qryValidContract(businessCompanys, "Contract.contractType.supplier"):
                                                        contractRepository.qryValidContract(businessCompanys, "Contract.contractType.supplier",supplierIds);
            if (purchaseContracts.size() != 0) contracts.addAll(purchaseContracts);
        } else {
            contracts.addAll(supplierIds.isEmpty()?contractRepository.accordingSupplierQuery(businessCompanys, "Contract.contractType.supplier"):
                                                    contractRepository.accordingSupplierQuery(businessCompanys, "Contract.contractType.supplier",supplierIds));
        }
        contracts = contracts.stream().distinct().collect(Collectors.toList());
        return contracts;
    }
    private List getPriceSupplier(JSONArray priceArray) {
        List supplierIds = new ArrayList();
        priceArray.forEach(price -> {
            JSONObject priceObj = (JSONObject) price;
            if (priceObj.getDoubleValue("P001") > 0 && !priceObj.getString("SUPPLIER_ID").equals("A00000"))
                supplierIds.add(priceObj.getString("SUPPLIER_ID"));
        });
        return supplierIds;
    }

    /** 计算裸价
     * 1. 询价执行表且1001不需要再加价
     * 2. 对非 1007 平台
     * */
    private double getUnP001(double P001, double P101, boolean isPlatForm, String isXJ) {
        if (isPlatForm || ("TRUE".equals(isXJ) && !isPlatForm)) return P001;
        return P001 * (1 + P101 / 100);
    }

    /** 获取税率 */
    private void getTax(String companyId, String supplierId, String productId, JSONObject newPurchaseRequireItems) {
        SimpleRequest requestCondition = new SimpleRequest();
        JSONObject getTaxCondi = new JSONObject();
        getTaxCondi.put("supplierId", supplierId);
        getTaxCondi.put("productId", productId);
        requestCondition.setData(getTaxCondi);
        Tax tax = taxService.getPurchaseTax(partyRoleRepository.findOne(companyId), partyRoleRepository.findOne(supplierId), productRepository.findOne(productId));
        newPurchaseRequireItems.put("tax", MapUtil.mapper("id", tax.getId(), "name", tax.getName()));
    }

    /** 拼接采购订单主表 */
    private void appendPurchasOrder(PurchaseOrder purchaseOrder, JSONObject expandInfoObj, String personId, String note) {
        if (StringUtils.isEmpty(expandInfoObj.getString("supplierId"))) return;
        personId = StringUtils.isEmpty(personId)?"system":personId;
        String sceneId = "PO001";
        if ("004465".equals(expandInfoObj.getString("supplierId"))) sceneId = "PO003";
        purchaseOrder.setState("sent");
        purchaseOrder.setScene(SpringManager.getBean(SceneRepository.class).findOne(sceneId));
        purchaseOrder.setClerk(partyRoleRepository.findOne(personId));
        purchaseOrder.setCreator(personId);
        purchaseOrder.setCreateUid(partyRoleRepository.findOne(personId));
        purchaseOrder.setCreateDate(new Date());
        Contract contract = contractRepository.findOne(expandInfoObj.getString("contractId"));
        purchaseOrder.setContract(contract);
        purchaseOrder.setCooperation(contract.getCooperation());
        purchaseOrder.setDept(deptRepository.findOne(expandInfoObj.getString("deptId")));
        purchaseOrder.setSupplier(partyRoleRepository.findOne(expandInfoObj.getString("supplierId")));
        purchaseOrder.setMoveType(contract.getMoveType() == null?SpringManager.getBean(EnumerationRepository.class).findOne("direct"):contract.getMoveType());
        purchaseOrder.setLocation(locationRepository.findOne(expandInfoObj.getString("locationId")));
        purchaseOrder.setCompany(partyRoleRepository.findOne(expandInfoObj.getString("companyId")));
     /*   if ("1007".equals(contract.getCompany().getId()) && !"001661".equals(purchaseOrder.getLocation().getCompany().getParty().getCorporate().getId())) {
            purchaseOrder.setCompany(purchaseOrder.getLocation().getCompany());
        } else {
            purchaseOrder.setCompany(purchaseOrder.getLocation().getCompany());
        }*/
        purchaseOrder.setCarLicense(expandInfoObj.getString("carLicense"));
        purchaseOrder.setProductRequire(expandInfoObj.getString("productRequireId"));
        purchaseOrder.setSource(expandInfoObj.getString("productRequireId"));
        purchaseOrder.setSourceType("ProductRequire");
        purchaseOrder.setSourceTypeName("赋能要货单");
        purchaseOrder.setNote(StringUtils.hasText(note)?note:"要货补货管理-采购");
//        JSONArray siteInfoArray = expandInfoObj.getJSONArray("site");
//        if (siteInfoArray != null && siteInfoArray.size() != 0) purchaseOrder.setSiteId(siteInfoArray.getJSONObject(0).getString("id"));
        if (StringUtils.hasText(expandInfoObj.getString("purchasingGroupId")) && StringUtils.isEmpty(expandInfoObj.getString("siteId"))) {
            Map purchaseGroupSite = invoke("cm.purchasingGroup.queryPurchaseGroupSite", MapUtil.mapper("id", expandInfoObj.getString("purchasingGroupId"), "locationId", expandInfoObj.getString("locationId")));
            purchaseOrder.setSiteId(purchaseGroupSite.get("siteId").toString());
        } else {
            purchaseOrder.setSiteId(expandInfoObj.getString("siteId"));
        }

        purchaseOrder.setPurchasingGroup(expandInfoObj.getString("purchasingGroupId"));
    }

    /** 拼接采购订单明细 */
    private void appendPurchaseOrderItem(PurchaseOrder purchaseOrder, List<PurchaseOrderItem> orderItemSet, JSONObject requireItemObj) {
        PurchaseOrderItem orderItem = new PurchaseOrderItem();
        double distributionQty = requireItemObj.getDoubleValue("distributionQty");
        double P001 = requireItemObj.getDoubleValue("P001");

        orderItem.setSourceState(SpringManager.getBean(EnumerationRepository.class).findOne(requireItemObj.getString("sourceStateId")));
        orderItem.setPurchaseOrder(purchaseOrder);
        orderItem.setProduct(productRepository.findOne(requireItemObj.getJSONObject("product").getString("id")));
        orderItem.setTax(SpringManager.getBean(TaxRepository.class).findOne(requireItemObj.getJSONObject("tax").getLong("id")));
        orderItem.setUom(productUomRepository.findOne(requireItemObj.getJSONObject("requireUom").getLong("id")));
        orderItem.setProductUomQty(distributionQty);
        orderItem.setEffectiveQty(distributionQty);
        orderItem.setDemandQty(distributionQty);
        orderItem.setPriceUnit(P001);

        Map getPriceCondi = new HashMap();
        getPriceCondi.put("companyId", purchaseOrder.getCompany().getId());
        getPriceCondi.put("taxId", requireItemObj.getJSONObject("tax").getLongValue("id"));
        getPriceCondi.put("priceUnit", P001);
        getPriceCondi.put("qty", distributionQty);
        Map reponsePrice = invoke("account.tax.computeTaxAmount", getPriceCondi);
        orderItem.setPriceSubtotal(Double.parseDouble(reponsePrice.get("totalExcluded").toString()));
        orderItem.setPriceTax(Double.parseDouble(reponsePrice.get("taxAmt").toString()));
        orderItem.setPriceTotal(Double.parseDouble(reponsePrice.get("totalIncluded").toString()));
        orderItem.setPriceCeiling(requireItemObj.getDoubleValue("priceCeiling"));
        orderItem.setExpectedArrivalTime(requireItemObj.getDoubleValue("expectedArrivalTime"));
        orderItem.setSourceState(SpringManager.getBean(EnumerationRepository.class).findOne(requireItemObj.getString("sourceStateId")));
        orderItemSet.add(orderItem);
    }

    /** 拼接采购订单 */
    private void appendCGDD(PurchaseOrder purchaseOrder, JSONObject cgddObj, String bz) {
        cgddObj.put("CGDDH", "");
        cgddObj.put("CZY", purchaseOrder.getCreator());
        cgddObj.put("DJLXID", "CD0");
        cgddObj.put("DJLXMC", "采购订货单");
        cgddObj.put("BZ", StringUtils.hasText(bz)?bz : "要货补货管理-采购"); // 固定并使用
        cgddObj.put("LYDJLX", purchaseOrder.getSourceType());
        cgddObj.put("LYDJMC", purchaseOrder.getSourceTypeName());
        cgddObj.put("LYDJHM", purchaseOrder.getProductRequire());
        cgddObj.put("CGHTH", purchaseOrder.getContract().getId());
        cgddObj.put("CGZZID", purchaseOrder.getCompany().getId());
        cgddObj.put("CGZZMC", purchaseOrder.getCompany().getName());

        cgddObj.put("CPHM", purchaseOrder.getCarLicense());
        if (StringUtils.hasText(purchaseOrder.getProductRequire())) {
            ProductRequire productRequire = SpringManager.getBean(ProductRequireRepository.class).findOne(purchaseOrder.getProductRequire());
            cgddObj.put("PZCXID", productRequire.getCustomerExpand().getJekunModelCode());
            cgddObj.put("CJHM", productRequire.getCustomerExpand().getVin());
        }

//        cgddObj.put("PTID", "1007");
//        cgddObj.put("PTMC", "广州市车宝网络科技有限公司");

        List<ContrastPartyCode> contrastPartyCode = contrastPartyCodeRepository.findAll(JpaDsl.toCriteriaByEq("party.id", purchaseOrder.getSupplier().getParty().getId()));
        if (contrastPartyCode.size() == 0) {
            throw new RuntimeException("请配置角色对照表对应的供应商！");
        }
        cgddObj.put("GYSID", contrastPartyCode.get(0).getGysid());
        cgddObj.put("HZFS", "distribution".equals(purchaseOrder.getContract().getCooperation().getId())?0:1);
        String settlementType = purchaseOrder.getContract().getSettlementType().getCode();
        int jszq = "bill".equals(settlementType)?0:"week".equals(settlementType)?1:"halfMonth".equals(settlementType)?2:"month".equals(settlementType)?3:"totalCash".equals(settlementType)?4:"deptCash".equals(settlementType)?5:0;
        cgddObj.put("JSZQ", jszq);
        cgddObj.put("JHFSID", "Contract.carryType.selfMention".equals(purchaseOrder.getContract().getCarryType().getId())?"10":"60");
        cgddObj.put("JHFSMC", "Contract.carryType.selfMention".equals(purchaseOrder.getContract().getCarryType().getId())?"自提":"送货");
        cgddObj.put("DHSX", 0);
        PartyRole ryInfo = new PartyRole();
        if (StringUtils.hasText(purchaseOrder.getPurchasingGroup())) {
            List<Map> getPurchaseGroupOperators = invoke("cm.purchasingGroup.getPurchaseGroupOperator", MapUtil.mapper("purchaseingId", purchaseOrder.getPurchasingGroup()));
            if (getPurchaseGroupOperators.size() == 0) {
                ryInfo = partyRoleRepository.findOne("system");
            } else {
                ryInfo = partyRoleRepository.findOne(getPurchaseGroupOperators.get(0).get("OPERABLE_ID").toString());
            }
        } else {
            ryInfo = partyRoleRepository.findOne("system");
        }

        cgddObj.put("RYID", ryInfo.getId());
        cgddObj.put("RYMC", ryInfo.getName());

        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        Calendar currentdate = Calendar.getInstance();
        currentdate.add(Calendar.DATE, 30);

        cgddObj.put("YQSHRQ", fmt.format(currentdate.getTime()));

        cgddObj.put("DJZT", 0);
        cgddObj.put("DHZJE", purchaseOrder.getAmtTotal());
        cgddObj.put("RKZJE", 0); // ????
        cgddObj.put("SQYFBJ", 0);

        cgddObj.put("ZDR", partyRoleRepository.findOne(purchaseOrder.getCreator()).getName());
        cgddObj.put("GSID", purchaseOrder.getCompany().getId());
        cgddObj.put("SPSX", 0);
        cgddObj.put("DHZSL", Arith.round(purchaseOrder.getPurchaseItems().stream().mapToDouble(purchaseOrderItem -> purchaseOrderItem.getProductUomQty()).sum(), 2));
        cgddObj.put("ZQTS", 0);
//        cgddObj.put("CPHM", purchaseOrder);
//        cgddObj.put("PTID", purchaseOrder.getCompany().getId());
//        cgddObj.put("PTMC", purchaseOrder.getCompany().getName());
        cgddObj.put("CGZID", purchaseOrder.getPurchasingGroup());

        Map siteInfo = invoke("tms.site.oldPhyDepotAddress", MapUtil.mapper("site_id", purchaseOrder.getSiteId()));
        cgddObj.put("ZDID", purchaseOrder.getSiteId());
        cgddObj.put("ZDMC", siteInfo.get("NAME"));
        cgddObj.put("ZZZSHDZ", siteInfo.get("ADDRESS"));

    }

    /** 拼接采购订单明细 */
    private void appendCGDDMX(PurchaseOrder purchaseOrder, String gorupKey, JSONArray CGDDMXArray, Map storageRequireItemIds) {
        purchaseOrder.getPurchaseItems().forEach(purchaseOrderItem -> {
            JSONObject CGDDMXObj = new JSONObject();
            if (purchaseOrderItem.getSourceState() != null && gorupKey.equals(purchaseOrderItem.getSourceState().getId())) {
                CGDDMXObj.put("XH", storageRequireItemIds.get(purchaseOrderItem.getProduct().getId()));
                CGDDMXObj.put("CKKQID", purchaseOrder.getLocation().getId());
                CGDDMXObj.put("CKKQMC", purchaseOrder.getLocation().getName());
                CGDDMXObj.put("CKID", purchaseOrder.getLocation().getPhyDepot().getId());
                CGDDMXObj.put("CKMC", purchaseOrder.getLocation().getPhyDepot().getName());
                CGDDMXObj.put("KQID", purchaseOrder.getLocation().getUsage().getId());
                CGDDMXObj.put("KQMC", purchaseOrder.getLocation().getUsage().getName());
                CGDDMXObj.put("CCTJID", 10);
                CGDDMXObj.put("SPID", purchaseOrderItem.getProduct().getId());
                CGDDMXObj.put("SPMC", purchaseOrderItem.getProduct().getName());
                CGDDMXObj.put("PLMC", purchaseOrderItem.getProduct().getClassify().getName());
                CGDDMXObj.put("PPID", purchaseOrderItem.getProduct().getBrand().getId());
                CGDDMXObj.put("PPMC", purchaseOrderItem.getProduct().getBrand().getName());
                CGDDMXObj.put("SPZID", purchaseOrderItem.getProduct().getProductGroup().getId());
                CGDDMXObj.put("SPZMC", purchaseOrderItem.getProduct().getProductGroup().getName());
                CGDDMXObj.put("SPXH", purchaseOrderItem.getProduct().getModel());
                CGDDMXObj.put("GG", purchaseOrderItem.getProduct().getSpecifications());
                CGDDMXObj.put("JLDW", purchaseOrderItem.getUom().getName());
                CGDDMXObj.put("HSBL", purchaseOrderItem.getUom().getFactor());
                CGDDMXObj.put("DHDJ", purchaseOrderItem.getPriceUnit());
                CGDDMXObj.put("DHJS", purchaseOrderItem.getProductUomQty());
                CGDDMXObj.put("DHSL", purchaseOrderItem.getProductUomQty() * purchaseOrderItem.getUom().getFactor());
                CGDDMXObj.put("DHJE", purchaseOrderItem.getPriceTotal());
                CGDDMXObj.put("RKJS", 0);
                CGDDMXObj.put("RKSL", 0);
                CGDDMXObj.put("ZXJS", 0);
                CGDDMXObj.put("ZXSL", 0);
                CGDDMXObj.put("GSID", purchaseOrder.getCompany().getId());
                CGDDMXObj.put("SB", 0);
                CGDDMXObj.put("SSBL", purchaseOrderItem.getTax().getAmt() / 100);
                CGDDMXObj.put("RKZDJS", 0);
                CGDDMXObj.put("RKZDSL", 0);
                CGDDMXObj.put("ZGXJ", purchaseOrderItem.getPriceCeiling());
                CGDDMXObj.put("ZDXJ", 0);
                CGDDMXObj.put("HYZT", purchaseOrderItem.getSourceState().getCode());
                CGDDMXObj.put("KJHJS", 0);
                CGDDMXObj.put("SJDHJS", 0);
                CGDDMXObj.put("YFHJS", 0);
                CGDDMXObj.put("YJDHSC", purchaseOrderItem.getExpectedArrivalTime());
                CGDDMXObj.put("CGDHSC", purchaseOrderItem.getExpectedArrivalTime());
                CGDDMXObj.put("YCKKQID", purchaseOrder.getLocation().getId());
                CGDDMXObj.put("YCKKQMC", purchaseOrder.getLocation().getName());
                CGDDMXObj.put("YGYSID", purchaseOrder.getSupplier().getId());
                CGDDMXObj.put("YGYSMC", purchaseOrder.getSupplier().getName());
                CGDDMXObj.put("YCGZZID", purchaseOrder.getCompany().getId());
                CGDDMXObj.put("YCGZZMC", purchaseOrder.getCompany().getName());
                CGDDMXObj.put("SOLICITATION_QTY", 0);
                CGDDMXArray.add(CGDDMXObj);
            }
            /** 到货时间怎么处理? */
        });
    }

/*    @OutboxSubscriber(id="local:ReplenishmentManagementService.synCGDD", name="要货补货管理-采购同步老框架")
    public void synCGDD(OutboxPayloadWrapper outboxPayloadWrapper) {
        try {
            piManager.synErp("scmCgddService.insert", outboxPayloadWrapper.getPayload());
        } catch (Exception e) {
            e.getMessage();
            if (e.getMessage().indexOf("重复生成采购订单！") != 0) {
                e.getMessage();
            } else {
                throw new RuntimeException(e.getMessage());
            }
        }
    }*/
}
